Jishnuraj
Jishnuraj

Reputation: 139

Php Server Sent Event- Message sender and inbox

I'm trying to make some php message sender and receiver Pages. From the "Admin.php" page, administrator can send messages to the website visitors. And the "receiver.php" page is the visitor's inbox. Here is the codes: Admin.php:

<form method="post" action="sender.php">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>

Sender.php:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$message = $POST["message"];
echo "data: {$message}\n\n";
flush();
?>

Receiver.php:

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("sender.php");
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

why doesn't this work?

Upvotes: 0

Views: 226

Answers (1)

Darren Cook
Darren Cook

Reputation: 28913

The problem is that you are trying to use "sender.php" to do two things.

From the admin form you need to submit to one php script that will store the messages, in a database of some kind.

Then in "receiver.php" you need to connect to a different PHP script, whose job is to keep polling that database for new entries, and when it sees one it should send it to the client. This latter PHP script will run in an infinite loop.

Upvotes: 1

Related Questions