Page 1 of 1

Help with a function..?

Posted: Wed Mar 16, 2005 9:53 pm
by ron_j_m
I found this function while looking through the manual for fsockopen.
It says it "allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array" If I understand that right it means that it will download the contents of x amount of urls simultaniously?

It sounds pretty interesting and Ive tried a few things to make it work and havnt had any success. Hopefully someone here can help me out with this.
Any Ideas?

Code: Select all

//thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.

// function connects to an array of URLS at the same time
// and returns an array of results.

function multiHTTP ($urlArr) {

 $sockets = Array(); // socket array!
 $urlInfo = Array(); // info arr 
 //print_r ("$urlInfo");
 $retDone = Array();
 $retData = Array();
 $errno  = Array();
 $errstr  = Array();
 for ($x=0;$x<count($urlArr);$x++) {
  $urlInfo[$x] = parse_url($urlArr[$x]);
  $urlInfo[$x][port] = ($urlInfo[$x][port]) ? $urlInfo[$x][port] : 80;
  $urlInfo[$x][path] = ($urlInfo[$x][path]) ? $urlInfo[$x][path] : "/";
  $sockets[$x] = fsockopen($urlInfo[$x][host], $urlInfo[$x][port],$errno[$x], $errstr[$x], 30);print_r ("$urlInfo");
  socket_set_blocking($sockets[$x],FALSE);
  $query = ($urlInfo[$x][query]) ? "?" . $urlInfo[$x][query] : "";
  fputs($sockets[$x],"GET " . $urlInfo[$x][path] . "$query HTTP/1.0\r\nHost: " .
       $urlInfo[$x][host] . "\r\n\r\n");
 }
 // ok read the data from each one
 $done = false; echo $done;
 while (!$done) {
  for ($x=0; $x < count($urlArr);$x++) {
   if (!feof($sockets[$x])) {
   if ($retData[$x]) {
     $retData[$x] .= fgets($sockets[$x],128);
   } else {
     $retData[$x] = fgets($sockets[$x],128);
   }
   } else {
   $retDone[$x] = 1;
   }
  }
  $done = (array_sum($retDone) == count($urlArr));
 }
 return $retData; 
 

}
//Ive tried to pass urls like this and echo the return with no luck
$urlArr = array("http://yahoo.com/index.html","http://google.com/index.html");
multiHTTP ($urlArr);

echo $retData;
Ron

Posted: Wed Mar 16, 2005 10:09 pm
by feyd
your code doesn't store the return from the function.

Posted: Wed Mar 16, 2005 10:25 pm
by ron_j_m
OK thanks..Sometimes things are just to easy to overlook ..