Using Sockets in PHP [轉載]

來源:互聯網
上載者:User

Using Sockets in PHP by 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 would 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 would 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 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.

 

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><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().

 

Whois Example

So you have learned how to connect to servers, fetch results, loop through results and finally close connections. So I thought I would 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 ease.

Conclusion

By now if you have followed this tutorial stage by stage you should know how to:

  • 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 should now realise 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.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.