In the following section you will learn how to send a request to a server and then list how many lines the server returned for a particular page and then how to loop through the returned array to display the page. Once you have a socket open to a server the variable $fp or whatever you have called it acts like a file in many ways, meaning you can send variables to $fp and return results.
<?php /* Once again we connect to the server at example.com */ $host = "www.example.com"; $page = "/index.html"; $fp = fsockopen($host, 80, $errno, $errdesc) or die("Connection to $host failed"); /* Now we define the headers to be sent to the server GET means we want the page or we want the contents of it. We can use POST to send variables to that page and return the results as i will show you later in this tutorial. */ $request = "GET $page HTTP/1.0\r\n"; $request .= "Host: $host\r\n"; $request .= "Referer: $host\r\n"; /* Using fputs() we send the request to the server and then loop through the results and form an array called $page */ fputs($fp, $request); while(!feof($fp)){ $page[] = fgets($fp, 1024); } /* Close the connection and count how many lines the server returned for a certain page */ fclose($fp); echo "The server returned ".(count($page)). " Lines"; /* Loop through the page array and print each line to the browser. Here we use the for() statement. */ for($i=0; $i<count($page); $i++){ echo $page[$i]; } ?>
That shouldn't of been too hard because after the initial connection and when we returned the array with the request we only looped through the array and printed its contents to the browser. In the next section I will show you a example of connecting to multiple servers.