Long polling vs WebSocket in PHP: What to Choose for a Realtime Project

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 Does Your Site "Lag" in Real Time?

\n\n

Imagine you visit a stock exchange website, but the dollar exchange rate only updates after you reload the page. Or you send a message in a chat, but the recipient sees it 10 seconds later. Sound familiar? This is the pain of any developer trying to make an application "live."

\n\n

In the world of PHP, where each request lives a short life, implementing realtime features is a non-trivial task. Two main approaches come to the rescue — Long polling and WebSocket. Which one should you choose for your PHP project? Let's figure it out without fluff, with live code examples.

\n\n

What is Long Polling in PHP? A Long Request with a Secret

\n\n

Long polling is an elegant trick that allows you to simulate a realtime connection using regular HTTP requests. The client sends a request to the server, but the server does not respond immediately. It keeps the connection open until a new event occurs (e.g., a new message in a chat). As soon as the event occurs, the server sends a response, the client processes it, and immediately creates a new "long" request.

\n\n

How It Works in PHP: A Simple Example

\n\n

Suppose we have a simple chat. The client sends an AJAX request to a PHP script that "hangs" in a loop until a new message appears in the database.

\n\n
<?php\n// long_polling.php\nheader('Content-Type: application/json');\nheader('Cache-Control: no-cache');\n\n$lastMessageId = $_GET['last_id'] ?? 0;\n$timeout = 30; // wait up to 30 seconds\n$startTime = time();\n\nwhile (time() - $startTime < $timeout) {\n    // Simulate a DB check (in reality - a query to MySQL/PostgreSQL)\n    $newMessages = getNewMessagesFromDB($lastMessageId);\n    \n    if (!empty($newMessages)) {\n        echo json_encode([\n            'status' => 'success',\n            'messages' => $newMessages\n        ]);\n        exit;\n    }\n    \n    // Sleep for 1 second to avoid killing the CPU\n    sleep(1);\n}\n\n// If nothing came in 30 seconds\necho json_encode(['status' => 'timeout', 'messages' => []]);\nexit;\n?>
\n\n

On the client side (JavaScript) it looks like this:

\n\n
function startLongPolling(lastId) {\n    fetch('/long_polling.php?last_id=' + lastId)\n        .then(response => response.json())\n        .then(data => {\n            if (data.status === 'success') {\n                data.messages.forEach(msg => addMessageToChat(msg));\n                startLongPolling(data.messages[data.messages.length - 1].id);\n            } else {\n                startLongPolling(lastId); // timeout — just restart\n            }\n        })\n        .catch(() => setTimeout(() => startLongPolling(lastId), 1000));\n}\n
\n\n

Pros of Long Polling in PHP

\n
    \n
  • Simplicity of implementation — no additional servers or libraries needed. Everything works on regular Apache/Nginx + PHP-FPM.
  • \n
  • Compatibility — works everywhere HTTP is available. No issues with proxies or corporate firewalls.
  • \n
  • Low entry barrier — if you know PHP and AJAX, you can already do Long polling.
  • \n
\n\n

Cons of Long Polling

\n
    \n
  • Server load — each "long" request keeps a PHP-FPM process occupied. With 1000 users, you'll need 1000 processes.
  • \n
  • Latency — minimum latency = 1 second (due to sleep). If you reduce sleep, the CPU will start melting.
  • \n
  • Scaling complexity — Long polling doesn't play well with load balancers (you need to pin a user to a specific server).
  • \n
\n\n

WebSocket in PHP: True Realtime Without Compromises

\n\n

WebSocket is a full-duplex communication channel over TCP. After a handshake via HTTP,

Blogs

Book Recommendations