PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
36: Building a Simple Socket Server in PHP
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 functiondisk_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
TIMEandMEMrequests 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.
There are no comments for now.