Archive for the ‘PHP’ Category

Create Socket Connection in PHP

Friday, December 5th, 2008

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.

(more…)