Sempervivum Sempervivum - 1 year ago 124
PHP Question

server-sent-events: How to trigger sending

I read this about server sent events: There they give an example in PHP for sending an event. I've learned that the header instruction must be the very first instruction in a script. However I need to do some preprocessing before sending the event:

//Do some preprocessing in order the determine whether to send an event or not
if ($sendevent) {
header("Content-Type: text/event-stream\n\n");
// echo the data

Obviously this is not possible as "header" is not the first instruction. How to solve this problem? Can sending an event only be triggered by sending a request from the client?

Answer Source

The documentation for the header() function says:

Remember that header() must be called before any actual output is sent.

It means you can include any number of instructions but your script must not output anything before calling header(). Your if doesn't output anything, so it's fine.

Be careful not to have whitespace characters before the PHP opening tag.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download