Network Programming in PHP: From Sockets to Web Scraping

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Network Programming in PHP Is Not Scary, But Interesting

\n\n

When you hear "network programming," images of stern C++ developers conjuring low-level sockets or admins writing Python scripts for network monitoring immediately come to mind. And PHP? Isn't its destiny simply to output "Hello, World!" on a website?

\n\n

In reality, PHP is a powerful tool for network interaction. It can open sockets, make HTTP requests, work with WebSocket, and even parse other websites. And all this — without installing additional extensions (well, almost).

\n\n

In this article, we will break down the key techniques of network programming in PHP. You will learn how to write a simple TCP client, how to automate API requests, how to parse websites, and how to create your own chat on WebSocket. Let's go!

\n\n

1. Basics of Sockets in PHP

\n\n

Sockets are a low-level way for programs to communicate over a network. In PHP, working with sockets is implemented through the socket_* family of functions. They are available in the standard build but sometimes require enabling the sockets extension in php.ini.

\n\n

Creating a TCP Client

\n\n

Let's write a simple client that connects to a server (for example, to time.nist.gov — the time server) and reads the response:

\n\n
<?php\n$host = 'time.nist.gov';\n$port = 37;\n\n// Create a socket\n$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\nif ($socket === false) {\n    echo "Failed to create socket: " . socket_strerror(socket_last_error()) . "\\n";\n    exit;\n}\n\n// Connect\n$result = socket_connect($socket, $host, $port);\nif ($result === false) {\n    echo "Failed to connect: " . socket_strerror(socket_last_error($socket)) . "\\n";\n    exit;\n}\n\n// Read 4 bytes (time in NTP format)\n$bytes = socket_read($socket, 4);\nif ($bytes === false) {\n    echo "Read error: " . socket_strerror(socket_last_error($socket)) . "\\n";\n    exit;\n}\n\n// Close the socket\nsocket_close($socket);\n\n// Convert binary data to a number\n$time = unpack('N', $bytes)[1];\n// NTP time is counted from 1900, subtract 70 years (seconds)\n$unix_time = $time - 2208988800;\necho "Current time (UNIX): " . date('Y-m-d H:i:s', $unix_time) . "\\n";\n?>
\n\n

This code connects to the time server, reads 4 bytes (time in NTP format), and converts them into a readable date. Pay attention to error handling — this is critical in network programming.

\n\n

Creating a Simple TCP Server

\n\n

Now let's write our own mini-server that will accept connections and respond with "Hello, client!":

\n\n
<?php\n$host = '127.0.0.1';\n$port = 8080;\n\n$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);\nsocket_bind($server, $host, $port);\nsocket_listen($server, 5);\n\necho "Server started on $host:$port\\n";\n\nwhile (true) {\n    $client = socket_accept($server);\n    if ($client === false) {\n        continue;\n    }\n    $msg = "Hello, client!\\n";\n    socket_write($client, $msg, strlen($msg));\n    socket_close($client);\n}\nsocket_close($server);\n?>
\n\n

Run the script in the console (php server.php), then connect to it via telnet: telnet 127.0.0.1 8080. You will see the greeting.

\n\n

Tip: For real projects, use ready-made libraries like ReactPHP or Amp — they provide asynchronicity and a convenient API.

\n\n

2. HTTP Requests with cURL

\n\n

cURL is a Swiss Army knife for working with HTTP in PHP. It can do GET, POST, work with cookies, headers, proxies, and certificates. The curl extension is usually pre-installed.

\n\n

Basic GET Request

\n\n
<?php\n$ch = curl_init('https://api.github.com/repos/php/php-src');\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_USERAGENT, 'PHP Script');\n$response = curl_exec($ch);\n$http_code = curl_getinf                

Blogs

Book Recommendations