This has got me (and apparently ChatGPT) baffled
I am trying to get a PHP webhook endpoint to trigger a server side event. This works, but not when I try hitting the endpoint with a POST request. To test the POST was being recieved I also logged to a file and that works.
Here's my webhook endpoint:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Function to send SSE
function sendSSE($data) {
echo "data: $data\n\n";
ob_flush();
flush();
}
sendSSE(json_encode(array("inn" => "inn"))); #1 This sends a server side event
file_put_contents('messages.log', "inn" . PHP_EOL, FILE_APPEND); #2 This writes to the log file
$post_data = file_get_contents("php://input");
if( $post_data != null ) {
file_put_contents('messages.log', "post2" . PHP_EOL, FILE_APPEND);
sendSSE(json_encode(array("post2" => "post2")));
}
// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
sendSSE(json_encode(array("post" => "post"))); #3 This DOES NOT a server side event
file_put_contents('messages.log', "post" . PHP_EOL, FILE_APPEND); #4 This DOES write to the log file
}
?>
And here's the client page I want to write the POST data to
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Client</title>
</head>
<body>
<div id="sse-data"></div>
<script>
const sseData = document.getElementById('sse-data');
const source = new EventSource('sse2.php');
source.onmessage = function(event) {
console.error("Onmessage received:", event);
const data = JSON.parse(event.data);
sseData.innerHTML += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
};
source.onerror = function(event) {
console.error("EventSource failed:", event);
};
</script>
</body>
</html>
I've also tried this with no joy
$post_data = file_get_contents("php://input");
if( $post_data != null ) {
file_put_contents('messages.log', "post2" . PHP_EOL, FILE_APPEND); # WORKS
sendSSE(json_encode(array("post2" => "post2"))); # DOES NOT WORK
}