Skip to content

Instantly share code, notes, and snippets.

@ludndev
Created March 14, 2025 00:59
Show Gist options
  • Save ludndev/f19ddbf7ac512f6a0672f90544a9bf47 to your computer and use it in GitHub Desktop.
Save ludndev/f19ddbf7ac512f6a0672f90544a9bf47 to your computer and use it in GitHub Desktop.
PHP SSE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Output</title>
</head>
<body>
<h1>Live Output:</h1>
<pre id="output"></pre>
<script>
const eventSource = new EventSource("sse.php");
eventSource.onmessage = function(event) {
document.getElementById("output").innerText += event.data + "\n";
};
eventSource.onerror = function() {
console.error("SSE connection lost.");
eventSource.close();
};
</script>
</body>
</html>
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo "data: Starting process...\n\n";
flush();
$cmd = '/bin/ping -c 5 google.com';
$descriptors = [
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'] // stderr
];
$process = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($process)) {
echo "data: Error: Failed to start process\n\n";
flush();
exit;
}
-
if (!isset($pipes[1]) || !isset($pipes[2]) || !is_resource($pipes[1]) || !is_resource($pipes[2])) {
echo "data: Error: Pipe creation failed\n\n";
flush();
proc_close($process);
exit;
}
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
while (true) {
$stdout = fgets($pipes[1]) ?: "";
$stderr = fgets($pipes[2]) ?: "";
if (!empty($stdout)) {
echo "data: " . trim($stdout) . "\n\n";
ob_flush();
flush();
}
if (!empty($stderr)) {
echo "data: [ERROR] " . trim($stderr) . "\n\n";
ob_flush();
flush();
}
$status = proc_get_status($process);
if (!$status['running']) {
break;
}
usleep(100000); // wait to aviod buffer overflow
}
// close all pipes
foreach ($pipes as $pipe) {
if (is_resource($pipe)) {
fclose($pipe);
}
}
proc_close($process);
echo "data: Done!\n\n";
flush();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment