PHPackages                             hhxsv5/php-sse - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. hhxsv5/php-sse

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

hhxsv5/php-sse
==============

A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.

v2.0.2(5y ago)452178.0k↑16.7%51[7 issues](https://github.com/hhxsv5/php-sse/issues)3MITPHPPHP &gt;=5.4CI failing

Since Jul 24Pushed 5y ago12 watchersCompare

[ Source](https://github.com/hhxsv5/php-sse)[ Packagist](https://packagist.org/packages/hhxsv5/php-sse)[ Docs](https://github.com/hhxsv5/php-sse)[ RSS](/packages/hhxsv5-php-sse/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (14)Used By (3)

PHP SSE: Server-sent Events
===========================

[](#php-sse-server-sent-events)

A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.

Requirements
------------

[](#requirements)

- PHP 5.4 or later

Installation via Composer([packagist](https://packagist.org/packages/hhxsv5/php-sse))
-------------------------------------------------------------------------------------

[](#installation-via-composerpackagist)

```
composer require "hhxsv5/php-sse:~2.0" -vvv
```

Usage
-----

[](#usage)

### Run demo

[](#run-demo)

- Run PHP webserver

```
cd examples
php -S 127.0.0.1:9001 -t .
```

- Open url `http://127.0.0.1:9001/index.html`

[![Demo](https://raw.githubusercontent.com/hhxsv5/php-sse/master/sse.png)](https://raw.githubusercontent.com/hhxsv5/php-sse/master/sse.png)

### Javascript demo

[](#javascript-demo)

> Client: receiving events from the server.

```
// withCredentials=true: pass the cross-domain cookies to server-side
const source = new EventSource('http://127.0.0.1:9001/sse.php', {withCredentials: true});
source.addEventListener('news', function (event) {
    console.log(event.data);
    // source.close(); // disconnect stream
}, false);
```

### PHP demo

[](#php-demo)

> Server: Sending events by pure php.

```
use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\SSE;
use Hhxsv5\SSE\StopSSEException;

// PHP-FPM SSE Example: push messages to client

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // Nginx: unbuffered responses suitable for Comet and HTTP streaming applications

$callback = function () {
    $id = mt_rand(1, 1000);
    $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
    if (empty($news)) {
        return false; // Return false if no new messages
    }
    $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
    if ($shouldStop) {
        throw new StopSSEException();
    }
    return json_encode(compact('news'));
    // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
    // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
};
(new SSE(new Event($callback, 'news')))->start();
```

### Symfony and Laravel demo

[](#symfony-and-laravel-demo)

> Server: Sending events by Laravel or Symfony.

```
use Hhxsv5\SSE\SSE;
use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\StopSSEException;

// Action method in controller
public function getNewsStream()
{
    $response = new \Symfony\Component\HttpFoundation\StreamedResponse();
    $response->headers->set('Content-Type', 'text/event-stream');
    $response->headers->set('Cache-Control', 'no-cache');
    $response->headers->set('Connection', 'keep-alive');
    $response->headers->set('X-Accel-Buffering', 'no'); // Nginx: unbuffered responses suitable for Comet and HTTP streaming applications
    $response->setCallback(function () {
        $callback = function () {
            $id = mt_rand(1, 1000);
            $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
            if (empty($news)) {
                return false; // Return false if no new messages
            }
            $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
            if ($shouldStop) {
                throw new StopSSEException();
            }
            return json_encode(compact('news'));
            // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
            // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
        };
        (new SSE(new Event($callback, 'news')))->start();
    });
    return $response;
}
```

### Swoole demo

[](#swoole-demo)

> Server: Sending events by Swoole Coroutine Http Server. Install [Swoole](https://github.com/swoole/swoole-src) 4.5.x: `pecl install swoole`.

```
use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\SSESwoole;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
use Hhxsv5\SSE\StopSSEException;

// Swoole SSE Example: push messages to client

$server = new Server('0.0.0.0', 5200);
$server->set([
    'enable_coroutine'   => true,
    'max_coroutine'      => 10000, // worker_num*10000
    'reactor_num'        => swoole_cpu_num() * 2,
    'worker_num'         => swoole_cpu_num() * 2,
    'max_request'        => 100000,
    'buffer_output_size' => 4 * 1024 * 1024, // 4MB
    'log_level'          => SWOOLE_LOG_WARNING,
    'log_file'           => __DIR__ . '/swoole.log',
]);

$server->on('Request', function (Request $request, Response $response) use ($server) {
    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Content-Type', 'text/event-stream');
    $response->header('Cache-Control', 'no-cache');
    $response->header('Connection', 'keep-alive');
    $response->header('X-Accel-Buffering', 'no');

    $event = new Event(function () {
        $id = mt_rand(1, 1000);
        $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
        if (empty($news)) {
            return false; // Return false if no new messages
        }
        $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
        if ($shouldStop) {
            throw new StopSSEException();
        }
        return json_encode(compact('news'));
        // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
        // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
    }, 'news');
    (new SSESwoole($event, $request, $response))->start();
});
$server->start();
```

License
-------

[](#license)

[MIT](https://github.com/hhxsv5/php-sse/blob/master/LICENSE)

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity54

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 76.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~109 days

Recently: every ~89 days

Total

13

Last Release

1902d ago

Major Versions

v1.1.8 → v2.0.02020-06-30

### Community

Maintainers

![](https://www.gravatar.com/avatar/25aef9db96e7295dedf20a48e81eb69dcfd3b2cae12859d37aa90c8a6c53e720?d=identicon)[hhxsv5](/maintainers/hhxsv5)

---

Top Contributors

[![hhxsv5](https://avatars.githubusercontent.com/u/7278743?v=4)](https://github.com/hhxsv5 "hhxsv5 (29 commits)")[![fabianofa](https://avatars.githubusercontent.com/u/3268899?v=4)](https://github.com/fabianofa "fabianofa (3 commits)")[![DeepDiver1975](https://avatars.githubusercontent.com/u/1005065?v=4)](https://github.com/DeepDiver1975 "DeepDiver1975 (2 commits)")[![dunglas](https://avatars.githubusercontent.com/u/57224?v=4)](https://github.com/dunglas "dunglas (2 commits)")[![mlazze](https://avatars.githubusercontent.com/u/19763535?v=4)](https://github.com/mlazze "mlazze (2 commits)")

---

Tags

event-streameventseventsourceserver-sent-eventssever-eventssseeventssseserver sent eventseventsourcesever-eventsevent-stream

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hhxsv5-php-sse/health.svg)

```
[![Health](https://phpackages.com/badges/hhxsv5-php-sse/health.svg)](https://phpackages.com/packages/hhxsv5-php-sse)
```

###  Alternatives

[doctrine/event-manager

The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.

6.1k501.1M115](/packages/doctrine-event-manager)[psr/event-dispatcher

Standard interfaces for event handling.

2.3k618.8M865](/packages/psr-event-dispatcher)[laminas/laminas-eventmanager

Trigger and listen to events within a PHP application

1.0k69.8M225](/packages/laminas-laminas-eventmanager)[simshaun/recurr

PHP library for working with recurrence rules

1.6k15.7M40](/packages/simshaun-recurr)[mvanduijker/laravel-mercure-broadcaster

Mercure broadcaster

16866.5k](/packages/mvanduijker-laravel-mercure-broadcaster)[symfony/mercure

Symfony Mercure Component

44015.1M28](/packages/symfony-mercure)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
