Using sockets in PHPBy Andrew Walsh |
|
Introduction
Sockets are a method in which PHP can connect to another server over the Internet and networks. the basic function to open a socket to a server is fsockopen (). you may be wondering why you wowould want to connect to another server? If you need to obtain information from a 3rd party server then sockets are for you.
Making the connection
You may think connecting to another Internet server is difficult but you wocould be wrong. you can establish a connection in just one line of PHP code. in this section I will show you how to simply connect and disconnect using sockets.
<?php /* Arguments that fsockopen takes: fsockopen(Hostname/IP, Port Number, Error Number Variable, Error Description Variable) The error number variable and error description variable are populated only on failure of fsockopen. $errno will contain the error number and $errdesc will contain the error description e.g. Server cannot be found. */ $fp = fsockopen( "www.example.com", 80, $errno, $errdesc); ?> |
Now that we have established a connection to the server at example.com let's close the connection. You might be familiar with the fclose () function, we use this to close the connection.
<?php $fp = fsockopen( "www.example.com", 80, $errno, $errdesc); //establish connection fclose($fp); //close connection ?> |
Now lets move on to more useful things related to sockets on the next page.
Sending the request
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 particle page and then how to loop through the returned array to display page. once you have a socket open to a server the variable $ FP or whatever you have called it acts like a file in always 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.
Searching for a page
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>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 ().
Whois example
So you have learned how to connect to servers, fetch results, loop through results and finally close connections. so I thought I wocould include a more practical example in this section and I chose to do a whois example which connects to certain Whois servers and checks for a record for a certain domain.
<?php extract($_POST); function whois($domain,$ext){ $url=$domain.$ext; /* Use a switch() statement to determine which whois server is the best to use for the entered domain. */ switch($ext){ case ".co.uk": $whois = "whois.nic.uk"; break; case ".com": $whois = "whois.networksolutions.com"; break; case ".fr": $whois = "whois.nic.fr"; break; case ".biz": $whois = "whois.biz"; break; default: $whois = "whois.networksolutions.com"; } if (trim($url) <> "") { $url = trim($url); /* Open the connection to the above whois server */ $f = fsockopen($whois, 43, $errno, $errstr, 30); if (!$f) { echo "Connection To Server Failed ($errno)"; } else { /* Send the domain to the server and return the results */ fputs($f, "$url/r/n"); print "<pre>/r/n"; while (!feof($f)) { echo fread($f,128); } print "</pre>"; /* Use fclose to close the connection to the whois server */ fclose($f); } }else{ echo "Invalid domain entered"; } } ?> |
Notice I have written this code in a function so it is more practical and reusable than the other examples in this tutorial. They can be coded up into a function with relative response.
Conclusion
By now if you have followed this tutorial stage by stage you shoshould know how:
- Connect to a server using sockets
- Disconnect from a server
- Send a request to a server
- List the number of lines returned by the server on a request
- Use sockets in a practical project like a whois look-up script
And you shoshould now realize that sockets and connecting to servers is both useful to know and easy to use.
About the author
Andrew Walsh lives in the UK and is engaged in his secondary education. he wishes to persue a higher education in computer studies. he started programming at the age of 13 years, currently he has knowledge of PHP/MySQL, HTML, CSS and JavaScript.