You might not know this, but PHP comes with a very capable socketprogramming API. These socket functions now include almost everything youwould need for socket-based client-server communication over TCP/IP, andcan be easily deployed to build simple network applications. Find out more,inside.
The steps demonstrated on the previous page make up a fairly standard process flow for constructing a socket server in PHP, and almost every server you create will follow the same basic steps. Consider the following example, which modifies the previous example to produce a random message from the "fortune" program every time a client connects to the server:
<?
// don't timeout!
set_time_limit(0);
// set some variables
$host = "192.168.1.99";
$port = 1234;
$command = "/usr/games/fortune";
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to
socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket
listener\n");
echo "Waiting for connections...\n";
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming
connection\n");
echo "Received connection request\n";
// run command and send back output
$output = `$command`;
socket_write($spawn, $output, strlen ($output)) or die("Could not write
output\n");
echo "Sent output: $output\n";
// close sockets
socket_close($spawn);
socket_close($socket);
echo "Socket terminated\n";
?>
In this case, I'm not even waiting to receive any data from
the client. Instead, I'm simply executing an external command (the "fortune" program) with PHP's backtick(`) operator, sending the results of the command to the client, and closing the connection. A trifle abrupt, but you know how rude young people are nowadays.
Note the addition of debug messages on the server side of the connection - these messages provide a handy way to find out the current status of the socket.
Here's an example of what a client sees when it connects to the socket,
$ telnet 192.168.1.99 1234
Trying 192.168.1.99...
Connected to medusa.
Escape character is '^]'.
Paradise is exactly like where you are right now ... only much, much better.
-- Laurie Anderson
Connection closed by foreign host.
and here are the corresponding debug messages generated on
the server:
$ /usr/local/bin/php -q server.php
Waiting for connections...
Received connection request
Sent output: Paradise is exactly like where you are right now ... only
much, much better.
-- Laurie Anderson
Socket terminated