Right in this section I will show you an example that uses fsockopen() to connect to a server. The example I will show you is how to connect to multiple webservers and check if a certain page is on that server.
<?php $servers = array( "www.example.com" => "/index.html", "www.example2.com" => "/index.php" ); /* loop through the servers array and then connect to the host and return an error if fsockopen couldn't connect to the server. */ foreach($servers as $host=> $page){ $fp = fsockopen($host,80,$errno,$errdesc,10); echo "Trying $host<br>\n"; if(!$fp){ echo("couldnt connect to $host"); echo "<br><hr><br>\n"; continue; } /* Print trying to get the page then define the request and send it to the server */ echo "trying to get $page<br>\n"; $request = "HEAD $page HTTP/1.0\r\n\r\n"; fputs($fp, $request); /* print the results to the browser */ echo fgets($fp, 1024); echo "<br><br><br>\n"; /* Once again close the connection with fclose() */ fclose($fp); /* Close the foreach loop */ } ?>
That piece of code will simply display something like this:
Trying: www.example.com Trying to get: /index.html HTTP/1.1 200 OK
That will be displayed only if the page was found. 404 Not found will replace 200 OK if the page wasn't found. You may recognize the 404 error as the exact same one as seen in your browser if you go to a page that doesn't exist.
In the next section I will show you how to get whois results for a domain name using fsockopen().