PHP
  Home arrow PHP arrow Page 3 - Emulating a Basic Web Server with Sockets in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Emulating a Basic Web Server with Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-06-05


    Table of Contents:
  • Emulating a Basic Web Server with Sockets in PHP
  • Taking a quick look at the previous TCP server
  • Emulating a Web server
  • Putting the Web server to work

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Emulating a Basic Web Server with Sockets in PHP - Emulating a Web server
    ( Page 3 of 4 )

    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='127.0.0.1',$port='12345',$docDir='defaultDir'){
            $this->docDir=$docDir;
            $this->host=$host;
            $this->port=$port;
            $this->createSocket();
            $this->readUserInput();
        }
        function createSocket(){
            set_time_limit(0);
            // create low level socket
            if(!$this->socket=socket_create(AF_INET,SOCK_STREAM,0)){
                trigger_error('Error creating new
    socket',E_USER_ERROR);
            }
            // tie up socket to TCP port
            if(!socket_bind($this->socket,$this->host,$this->port)){
                trigger_error('Error binding socket to TCP
    port',E_USER_ERROR);
            }
            // begin listening connections
            if(!socket_listen($this->socket)){
                trigger_error('Error listening socket
    connections',E_USER_ERROR);
            }
            // create communication socket
            if(!$this->comSocket=socket_accept($this->socket)){
                trigger_error('Error creating communication
    socket',E_USER_ERROR);
            }
            // display welcome message
            $message='Welcome to the Console Web Server! Please type
    below the file name you want to fetch...'."\r\n";
            socket_write($this->comSocket,$message,strlen($message));
        }
        // read user input
        function readUserInput(){
            // start a loop and continue reading user input
            do{
                // delay loop execution
                sleep(10);
                // read socket input
                $socketInput=socket_read($this->comSocket,1024);
                if(trim($socketInput)!=''){ 
                    // if user did not entered the 'STOP" command
    continue reading data
                    if(trim($socketInput)!='STOP'){
                        // convert to uppercase socket input 
                        $socketOutput=$this->fetchFile
    ($socketInput)."\r\n";
                        // write data back to socket server
                        socket_write($this-
    >comSocket,$socketOutput,strlen($socketOutput));
                    }
                    else{
                        // if 'STOP' command was entered close
    communication socket & terminate all the connections
                        socket_close($this->comSocket);
                        break;
                    }
                }
            }
            while(true);
            // close global socket
            socket_close($this->socket);
        }
        // fetch (X)HTML file
        function fetchFile($socketInput){
            $path='C:\\php\cli\\'.$this->docDir.'\\'.trim
    ($socketInput);
            if(!file_exists($path)){
                return 'File not found on this server. Please try
    again';
            }
            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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek