HomePHP Page 4 - Emulating a Basic Web Server with Sockets in PHP
Putting the Web server to work - PHP
Do you think that programming sockets with PHP is really hard work? Not at all. If you’re still not convinced, read this final part of the series “Handling sockets with PHP.” In three parts, this series shows how to work with low-level sockets in PHP. It introduces some of the typical tasks, such as creating sockets, as well as reading and writing socket data.
In order to see how the Web server works, first I’ll define an example “index.htm” web page, which will be saved to the default directory specified in the “WebServer” class. Below, I listed this sample web document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>TEST WEB DOCUMENT</title> <meta http-equiv="Content-Type" content="text/html; charset=iso- 8859-1" /> </head> <body> <h1>THIS IS AN EXAMPLE WEB PAGE</h1> </body> </html>
After defining the above (X)HTML file, the Web server will be run by a “webserver.php” file, which obviously will contain the corresponding definition of the “WebServer” class and use an instance of it, like this:
Now that both “index.htm” and “webserver.php” files have been defined respectively, take a look at the following screenshots, which illustrate how to use the Web server by utilizing a Telnet program as the client :
As shown above, the first screenshot depicts the process where the “index.htm” file is requested and then displayed. The second image shows the response of the server when trying to retrieve a non-existent file, as well as when the server is stopped by entering the STOP command.
Of course, I think this Web server won’t be capable of beating Apache, but the above example is enough to demonstrate the powerful capabilities of low-level sockets in PHP.
Finally, we’re done. In this new PHP series, you learned how to work with sockets in PHP through the development of different examples, such as creating a TCP server, and more specifically building an application that emulates a basic Web server.
In all the code samples, I used some of the most common PHP socket-related functions, therefore you shouldn’t have any problems using them as part of your own applications. See you in the next PHP tutorial!