PHP Socket Programming Tutorial

Every programming language enable to use socket programming to provide the communication mechanism between two processes on the same or different machine. PHP is the one of the programming language that able to use the socket. A Socket is mostly used in a client-server application framework. There have many application-level protocols like FTP, HTTP, and HTTPS to make use of sockets to establish connection between client and server.

Create a PHP file

Open your PHP editor and create a php file name “server”. Below is the server.php code and insert the following code.

Open command prompt

Open your cmd and type php (path)/(your-file-name). Way to open cmd : search cmd in the bottom bar.

php socket programming

Edit client.php file

After that create one more php file name “client” and insert the below code.

Open second command prompt

Open another command prompt,  insert the client.php path. Below are example.

Check client respond

After that, you will see the server(1st command prompt) respond from the client(2nd command prompt).

(PHP Socket Programming)

Source Code

(Visited 8,647 times, 9 visits today)
Advertisements

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

4 Responses

  1. cool says:

    I want to apply same on browser .. please help

  2. Femina F says:

    <?php
    error_reporting(E_ALL);
    set_time_limit(0);
    echo "TCP/IP Connection\n”;

    $port = 1935;
    $ip = “127.0.0.1”;

    /*
    +——————————-
    * @socketconectionprocess
    +——————————-
    * @socket_create
    * @socket_connect
    * @socket_write
    * @socket_read
    * @socket_close
    +——————————–
    */

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
    echo "socket_create() failed. reason: " . socket_strerror($socket) . "\n";
    }else {
    echo "OK.\n";
    }

    echo "Try to connect '$ip' Port '$port'…\n";
    $result = socket_connect($socket, $ip, $port);
    if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
    }else {
    echo "Connect OK\n";
    }

    $in = "Testing\r\n";
    $out = '';

    if(!socket_write($socket, $in, strlen($in))) {
    echo "socket_write() failed. reason: " . socket_strerror($socket) . "\n";
    }else {
    echo "Send Message to Server Successfully!\n";
    echo "Send Information:$in “;
    }

    while($out = socket_read($socket, 8192)) {
    echo “Receive Server Return Message Successfully!\n”;
    echo “Received Message:”,$out;
    }

    echo “Turn Off Socket…\n”;
    socket_close($socket);
    echo “Turn Off OK\n”;
    ?>

  3. Yas says:

    May you explain the server code?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *