Server-Sent Events in PHP: Real-Time Without WebSocket and Headaches

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

Server-Sent Events in PHP: Real-Time That Doesn't Bite

\n\n

Have you ever wondered why your favorite messenger or cryptocurrency exchange updates data instantly, while your PHP site still makes users press F5? It seems that real-time is the domain of the elite, armed with Node.js or expensive WebSocket servers. But what if I told you that Server-Sent Events (SSE) in PHP is a simple, elegant, and incredibly effective way to add live updates to your project?

\n\n

Welcome to PythonLib, where we break stereotypes. Today we'll dive into Server-Sent Events PHP — a technology that allows the server to "push" data to the client over plain HTTP, without a single line of JavaScript magic (well, almost without it). No complex protocols, no issues with NAT and proxies — just pure, understandable PHP and a data stream that flows like a mountain river.

\n\n

What are Server-Sent Events and Why Are They a "Silver Bullet" for PHP?

\n\n

SSE is an HTML5 specification that allows the server to send an arbitrary number of events to the client over a single long-lived HTTP connection. Unlike WebSocket, which is bidirectional, SSE works only "from server to client." And that's great! For 90% of tasks (notifications, news feeds, monitoring, stock tickers), feedback is not needed. Why drag heavy artillery when you can get by with light infantry weapons?

\n\n

Main advantages of real-time notifications PHP via SSE:

\n
    \n
  • Simplicity of implementation — on the server side, it's a regular PHP script that doesn't close the connection.
  • \n
  • Automatic reconnection — the browser reconnects on its own if the connection is lost.
  • \n
  • Works through any proxy — HTTP/1.1, HTTP/2, Nginx, Apache — all work out of the box.
  • \n
  • Low resource consumption — unlike polling, requests are not duplicated every 2 seconds.
  • \n
\n\n

Of course, SSE has limitations: the maximum number of simultaneous connections in a browser (6 per domain), and they are not supported in older Internet Explorer. But for modern applications, this is not a problem. And if you need more — use HTTP/2, where these limitations are removed.

\n\n

How Server-Sent Events Work in PHP: From Theory to Practice

\n\n

Let's imagine your PHP script is a bartender. A regular request is when a customer comes up, orders a drink (makes a GET request), the bartender pours (executes the code), hands over the glass (sends the response), and closes the bar. With SSE, the customer comes up, orders "please, pour me a new cocktail every 5 seconds," and the bartender starts an endless stream without turning off the tap.

\n\n

Technically, it looks like this:

\n
    \n
  1. The client (browser) creates an EventSource object and sends a GET request to the PHP script.
  2. \n
  3. The server sets the Content-Type: text/event-stream header and disables caching.
  4. \n
  5. The server enters an infinite loop, sending data in the format data: {"message": "hello"}\\n\\n.
  6. \n
  7. When the server needs to stop (or the client closes the tab), the connection is terminated.
  8. \n
\n\n

First Example: A Simple "Hello, World" on SSE in PHP

\n\n

Let's create a file sse.php. This will be our "perpetual motion machine":

\n\n
<?php\n// sse.php - simplest Server-Sent Events server\nheader('Content-Type: text/event-stream');\nheader('Cache-Control: no-cache');\nheader('Connection: keep-alive');\nheader('X-Accel-Buffering: no'); // for Nginx\n\n// Make sure PHP doesn't abort execution\nset_time_limit(0);\n\n$counter = 0;\n\nwhile (true) {\n    $counter++;\n    $data = ['time' => date('H:i:s'), 'count' => $counter];\n    \n    // Send the event\n    echo "id: {$counter}\\n";\n    echo "event: update\\n";\n    echo "data: " . json_encode($data) . "\\n\\n";\n    \n    //                

Blogs

Book Recommendations