PHP
  Home arrow PHP arrow Page 3 - An Introduction to Sockets in PHP
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

An Introduction to Sockets in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 21
    2006-05-22

    Table of Contents:
  • An Introduction to Sockets in PHP
  • The basics of low-level sockets: developing an illustrative example
  • Reading and writing socket data: creating a simple web-based client application
  • Reusing the TCP server: defining the "createSocketServer()" function and "SocketServer" class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


    An Introduction to Sockets in PHP - Reading and writing socket data: creating a simple web-based client application


    (Page 3 of 4 )

    Creating a client application to test the sample TCP server is a straightforward task. Essentially, I'll build a web-based script that will connect to the aforementioned server and send a string of data via an online form. In accordance with the logic implemented on the server, this string should be returned to the client in uppercase, and finally displayed on the browser.

    Here's the snippet of code that creates a simple web-based client, handy for testing the TCP server in question:

    <?php
    // check if form was submitted
    if($_POST['send']){
        // open client connection to TCP server
        if(!$fp=fsockopen('127.0.0.1',1234,$errstr,$errno,30)){
            trigger_error('Error opening socket',E_USER_ERROR);
        }
        $message=$_POST['message'];
        // write message to socket server
        fputs($fp,$message);
        // get server response
        $ret=fgets($fp,1024);
        // close socket connection
        fclose($fp);
        echo '<h1>You entered the following message in
    lowercase :'.$ret.'</h1>';
        exit();
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>TESTING TCP SOCKET SERVER</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    </head>
    <body>
    <h1>Enter your message here</h1>
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
    <input type="text" name="message" size="30" /><br />
    <input type="submit" name="send" value="Send Value" />
    </form>
    </body>
    </html>

    As you can appreciate, the above script uses the PHP "fsockopen()" function, in order to connect to the recently created TCP server and inject into the socket the string entered in the online form. After receiving the uppercase string, the script displays this data and finishes its execution.

    To understand the functionality of the sample TCP server, please take a look at the following screen shots, which illustrate both the client petition and the server response respectively:

    As depicted above, the images show the TCP server in action. First, the client submits a message via the online form, and secondly the server turns the input to an uppercase string, which is finally echoed to the browser.

    In addition, before I explain more concepts related to socket programming in PHP, I want to clarify one important point regarding the example: you should run the script that creates the TCP server from the PHP command line, instead of using your browser, in order to prevent the system from hanging. This can be done easily by using the CLI.exe file that comes with your PHP distribution and typing the following commands in your system shell:

    q- tcpserver.php

    The following screen shot shows how to start the TCP server using the PHP command line on a Windows system:

    Assuming that the TCP server has been coded in a file called "tcpserver.php," the above command should run this file and start the server (the preceding q flag tells the PHP interpreter to suppress the "Content-type" HTTP header). After making sure the server is up and running, you can point your browser to the PHP file that builds the corresponding client, and run the pertinent file.

    Right, now you see how the sockets I created in the previous section do their job, reading and writing the corresponding data. Since the example TCP server has been created with a few lines of procedural code, it'd be very convenient to encapsulate the whole source code within a compact function (and incidentally within a class), so the server can be reused as many times as needed.

    If you're interested in learning how this can be achieved, please read the next few lines of the article.

    More PHP Articles
    More By Alejandro Gervasio


       · This first article covers the most important functions related to creating,...
       · This one is the best tutorial i found on net.Good Work
       · Thank you for the kind comments on my PHP article. I really appreciate them and it's...
       · i comment over this topic previously it was great.i am using your server ex. to...
       · Thank you for commenting on my PHP article. Actually, I’m not sure to understand...
       · I was looking for an introduction of PHP network programming capabilities as I...
       · Thanks for the kind words on my PHP sockects article. Good to know it's been helpful...
     

       

    PHP ARTICLES

    - Using Aliases and the Autoload Function with...
    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Sub Classing Exceptions in PHP 5
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT