SSE writes event-stream frames over a long-lived HTTP response for one-way server updates.
What It Does and When to Use It
Emit an SSE event with the required blank-line separator. Direct PHP code exposes the underlying operation clearly; a framework can supply lifecycle hooks, dependency wiring and retries.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Disable output buffering where appropriate, handle disconnects and keep heartbeat intervals modest.
Example 1: Basic Operation
Emit an SSE event with the required blank-line separator.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo "event: ready
";
echo 'data: ', json_encode(['status' => 'ok'], JSON_THROW_ON_ERROR), "
";
flush();
Example 2: Behavior and Validation
Attach event IDs so a browser can resume from Last-Event-ID.
<?php
header('Content-Type: text/event-stream');
for ($id = 1; $id <= 3; $id++) {
echo "id: $id
";
echo 'data: ', json_encode(['progress' => $id * 25]), "
";
flush();
}
Practical Example: Application Use
Send a heartbeat and observe client disconnection; configure proxy buffering separately.
<?php
header('Content-Type: text/event-stream');
@ini_set('output_buffering', 'off');
while (ob_get_level() > 0) ob_end_flush();
echo ": keepalive
";
flush();
if (connection_aborted()) exit;
Important Behavior and Edge Cases
The second example highlights: Attach event IDs so a browser can resume from Last-Event-ID. The practical example adds: Send a heartbeat and observe client disconnection; configure proxy buffering separately.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Direct operation versus framework-managed integration | Direct PHP code exposes the underlying operation clearly; a framework can supply lifecycle hooks, dependency wiring and retries. |
| Choosing safely | Choose based on deployment requirements and verify actual behavior rather than assuming defaults. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming successful execution proves the result is usable | Check the return value, required extension, and observable output of the specific operation. |
| Ignoring runtime and environment differences | Verify PHP version, SAPI, operating system, service access, and permissions before deployment. |
| Skipping operational constraints | Disable output buffering where appropriate, handle disconnects and keep heartbeat intervals modest. |
Key Takeaways
- SSE writes event-stream frames over a long-lived HTTP response for one-way server updates.
- Send a heartbeat and observe client disconnection; configure proxy buffering separately.
- Choose based on deployment requirements and verify actual behavior rather than assuming defaults.