Skip to Content
Course content

36: Building a Simple Socket Server in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just do this with a normal PHP script in my browser?

This is the first thing most people ask. When you run PHP via Apache or Nginx, you're working in a "Request-Response" cycle. The web server handles the socket, hands the request to PHP, PHP spits out HTML, and then the process dies. It's ephemeral.

A socket server is different. We're bypassing the web server entirely and running PHP from the command line (CLI). We're telling the operating system, "I want to own this specific port, and I'm going to stay awake until I decide to stop." This is how you build things like chat servers, game backends, or custom IoT listeners. I'll warn you now: because the script stays alive, you have to be much more careful about memory leaks than you do in a standard web script.

How do I actually get the server to sit and wait for a connection?

To do this, we use the socket_ family of functions. It feels a bit like writing C because, under the hood, that's exactly what's happening. You have to create the socket, bind it to an address and port, and then tell it to listen.

$address = '127.0.0.1';
$port = 8080;

// 1. Create the socket (AF_INET = IPv4, SOCK_STREAM = TCP)
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// 2. Bind it to the IP and Port
socket_bind($socket, $address, $port);

// 3. Start listening (the '5' is the backlog of pending connections)
socket_listen($socket, 5);

echo "Server listening on $address:$port...\n";

// 4. Accept an incoming connection
$client = socket_accept($socket);
echo "Client connected!\n";

Notice that socket_accept is a "blocking" call. Your script will literally pause right there and do nothing until someone tries to connect to that port. If you're testing this locally, you can use a tool like Telnet or Netcat (nc localhost 8080) to trigger that connection.

How do I make the server actually respond to specific commands?

Once you have the $client socket, you can read data from it and write data back. To make it useful, we'll wrap the acceptance and reading process in a loop. Let's build a simple "System Status" server. Instead of a generic "Hello", we'll make it return the server's current time or memory usage based on what the client sends.

while (true) {
    $client = socket_accept($socket);
    
    // Read the input (up to 1024 bytes)
    $input = socket_read($client, 1024);
    $input = trim($input);

    switch ($input) {
        case 'TIME':
            $response = "Current Server Time: " . date('Y-m-d H:i:s') . "\n";
            break;
        case 'MEM':
            $usage = memory_get_usage() / 1024 / 1024;
            $response = "Memory Usage: " . round($usage, 2) . " MB\n";
            break;
        default:
            $response = "Unknown command. Try 'TIME' or 'MEM'.\n";
            break;
    }

    socket_write($client, $response, strlen($response));
    socket_close($client); // Close the client connection but keep the server alive
}

I used a switch statement here because it's cleaner when you're building a command-based protocol. Just remember to trim() the input. Clients often send a newline character (\n or \r\n) at the end of their message, which will break your string comparisons if you don't strip it off first.




📋 Practical Task

The Remote Server Resource Monitor

Your task is to expand the System Status Server. Modify the provided code to implement a third command: DISK.

  • When the client sends DISK, the server should use the PHP function disk_free_space("/") to find the remaining space on the root drive.
  • The response should be formatted in Gigabytes (GB) and rounded to two decimal places (e.g., "Free Disk Space: 42.15 GB").
  • Ensure the server continues to handle TIME and MEM requests correctly.

To test your work, run the script in your terminal and use nc localhost 8080 (on Linux/Mac) or a TCP testing tool on Windows to send the DISK command.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.