Home arrow PHP arrow Page 3 - Emulating a Basic Web Server with Sockets in PHP

Emulating a Web server - 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.

  1. Emulating a Basic Web Server with Sockets in PHP
  2. Taking a quick look at the previous TCP server
  3. Emulating a Web server
  4. Putting the Web server to work
By: Alejandro Gervasio
Rating: starstarstarstarstar / 10
June 05, 2006

print this article



Emulating the behavior of a real Web server with low-level sockets is a quite easy process to perform. In this case, I’m not going to use real HTTP commands like GET or POST requests, since it’d be rather pointless (probably you have a production-level Web server already installed on your computer), so instead I’ll create an “always-on” TCP server, which will be capable of fetching a specific (X)HTML file, according to the request made by a client.

At the end of this interaction, the contents of this file will be displayed to the user, in this way emulating the interactive process between a real Web server and the corresponding HTTP user agent.

Having explained how the Web server will work, here is the PHP class that precisely implements this application. Please, have a look at the code listed below:

// define 'WebServer' class
class WebServer {
    var $docDir;
    var $host;
    var $port;
    var $socket;
    var $comSocket;
    function WebServer($host='',$port='12345',$docDir='defaultDir'){
    function createSocket(){
        // create low level socket
            trigger_error('Error creating new
        // tie up socket to TCP port
            trigger_error('Error binding socket to TCP
        // begin listening connections
            trigger_error('Error listening socket
        // create communication socket
            trigger_error('Error creating communication
        // display welcome message
        $message='Welcome to the Console Web Server! Please type
below the file name you want to fetch...'."\r\n";
    // read user input
    function readUserInput(){
        // start a loop and continue reading user input
            // delay loop execution
            // read socket input
                // if user did not entered the 'STOP" command
continue reading data
                    // convert to uppercase socket input 
                    // write data back to socket server
                    // if 'STOP' command was entered close
communication socket & terminate all the connections
        // close global socket
    // fetch (X)HTML file
    function fetchFile($socketInput){
            return 'File not found on this server. Please try
        return file_get_contents($path);

As you can see, the above class, which I have amazingly called “WebServer,” implements a basic Web server by using some of the PHP socket-related functions you saw in previous tutorials. Its constructor takes up three arguments: the host to which a connection is established, the TCP port used by the server and the client in conjunction, and finally the physical directory where the server will fetch all the requested files.

In order to create a low-level socket and read/write data streams, the class additionally exposes the “createSocket()” method, which also calls the private “readUserInput()” method, handy for reading the name of the file being fetched. Finally, the “fetchFile()” method is tasked with retrieving the contents of the file specified by the client.

Before I proceed further, I’d like to clarify one important point: notice that the “fetchFile()” method uses the predefined “C:\php\cli” path, in order to fetch all the requested files. In this case, the server will be run on a Windows system, but if you’re working with Linux or some other operating system, you may want to change this directory and fetch files from another location.

Having addressed the topic mentioned before, it’s time to put this Web server to work. Please click on the link below to see an example that shows how the server will retrieve files requested by a Telnet client.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: