PHP server provide a method in which it can establish socket connection to communicate with other server. Many software applications including web server, instant messaging, and peer to peer file sharing systems rely on sockets. In other words, you can possibly create any web based application, ie. instant messaging client purely in PHP.
Open Connection
The basic function to open a socket connection is fsockopen(). You can establish a connection in just one line of PHP code, pretty simple uh?
//this method will open a connection and store a file handler to $fp variable,
//you can use fgets/fputs on it then later,
//if something goes wrong, you can check $errno and $errdesc variable
$fp=fsockopen("www.host.com",80,$errno,$errdesc);
After we established a connection, let’s close it by using fclose() method.
$fp=fsockopen("www.host.com",80,$errno,$errdesc);
fclose($fp);
Sending a Request
Now I will show you how to send a data (request) to a server and then check the response returned by the server. Once we open a socket, you can send any data to it, and wait for the response.
$fp=fsockopen("www.host.com",80,$errno,$errdesc) or
die("Connection to www.host.com failed");
$request="GET / HTTP/1.1\r\n";
$request.="Host: www.host.com\r\n";
$request.="Referer: www.host.com\r\n";
$request.="Connection: close\r\n";
$request.="\r\n";
fputs($fp,$request); //send the request
while(!feof($fp)){
$lines[] = fgets($fp, 1024);
}
foreach($lines as $line){ //display each lines
$line=htmlentities($line);
echo "LINE:".$line."";
}
fclose($socket); //don't forget to close connection
Using Socket in PHP – POP3 Email Example
Here is an example of socket connection to check POP3 email.
function sendcommand($fp,$command){
$response="";
fputs($fp, $command);
$response=fgets($fp,1024);
return $response;
}
function checkmail(){
$host="pop.host.com"; //PHP also support secure connection
//you can add "tls://" or "ssl://"
//to create secure connection
$port=110;
$username="username";
$password="password";
$fp=fsockopen($host,$port,$errno,$errstr,10);
$command="USER ".$username."\r\n"; //send username
$response=sendcommand($fp,$command);
echo "LINE:".$response."";
$command="PASS ".$password."\r\n"; //send password
$response=sendcommand($fp,$command);
echo "LINE:".$response."";
if(strstr($response,"+OK")!=""){ //accepted
$command="LIST"."\r\n";
$response=sendcommand($fp,$command);
echo "LINE:".$response."";
}
$command="QUIT"."\r\n";
$response=sendcommand($fp,$command);
echo "LINE:".$response."";
fclose($fp);
}
checkmail();
Now you have learned how to use socket in PHP, you can extend the usage for many purpose, like getting information from another web, query to whois server, check pop3/imap mail, instant messaging, online ftp client, and many more. And the most important thing, it is easy to implement.
Good luck on experimenting!
No related posts.
Tags: php fsockopen, socket connection