Socket Programming with PHP
TL;DR
PHP supports raw socket programming via the Sockets extension (socket_create) and stream sockets (stream_socket_client) — used for custom protocols, WebSocket servers, and network tools.
Explanation
Two socket APIs in PHP: (1) Sockets extension (socket_create, socket_bind, socket_listen, socket_accept) — low-level, POSIX-like. (2) Stream sockets (stream_socket_client, stream_socket_server) — higher level, supports SSL, uses fread/fwrite. For most cases, use Guzzle (HTTP), AMQP libraries (queues), or ReactPHP/Swoole for async sockets. Raw sockets are useful for: custom TCP/UDP protocols, network diagnostics, building WebSocket servers. Non-blocking sockets with socket_set_nonblock and socket_select() enable handling multiple connections. PHP's socket support is blocking by default — use ReactPHP or Swoole for production async networking.
Common Misconception
✗ PHP can't do real network server programming — it can, but blocking I/O limits scalability. Use ReactPHP/Swoole for production async socket servers.
Why It Matters
Understanding PHP socket APIs is essential for building custom protocol handlers, testing network services, and understanding how framework HTTP servers work.
Common Mistakes
- Using blocking sockets in production servers — limits to one connection at a time.
- Not setting SO_REUSEADDR — port in use errors after restart.
- Not handling partial reads — TCP streams can split messages across packets.
Code Examples
✗ Vulnerable
// Blocking TCP server — handles one connection at a time:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '0.0.0.0', 8080);
socket_listen($socket);
$client = socket_accept($socket); // Blocks until connection
✓ Fixed
// Non-blocking with stream sockets:
$server = stream_socket_server('tcp://0.0.0.0:8080', $errno, $errstr);
stream_set_blocking($server, false);
while (true) {
$client = @stream_socket_accept($server, 0);
if ($client) {
$data = fread($client, 1024);
fwrite($client, "HTTP/1.1 200 OK\r\n\r\nHello");
fclose($client);
}
// In production: use ReactPHP or Swoole for proper async
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
19
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
No pings yesterday
Amazonbot 7
Unknown AI 3
Perplexity 3
ChatGPT 2
Google 1
Ahrefs 1
Also referenced
How they use it
crawler 15
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: High
⚡ Quick Fix
Use stream_socket_client/server for SSL and simpler API. For production async: use ReactPHP or Swoole. Always set SO_REUSEADDR. Handle partial TCP reads.
📦 Applies To
PHP 5.0+
cli
ReactPHP
Swoole
🔗 Prerequisites
🔍 Detection Hints
socket_create|stream_socket
Auto-detectable:
✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: High
Context: File
Tests: Update