Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active May 4, 2020 18:56
Show Gist options
  • Save nezarfadle/9adfd1d6ad35484a415aa1d493c51997 to your computer and use it in GitHub Desktop.
Save nezarfadle/9adfd1d6ad35484a415aa1d493c51997 to your computer and use it in GitHub Desktop.
PHP Server Send Events
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<h1 id="log"></h1>
<button id="checkout">Check out</button>
<ul id="messages"></ul>

<script>

    let url = "http://localhost:9090"
    let btn = document.getElementById("checkout")
    let log = document.getElementById("log")
    let messages = document.getElementById("messages")
    

    btn.addEventListener("click", () => {
        
        let es = new EventSource( url )
    
        log.innerHTML ="Please wait ..."

        es.onmessage = e =>
        {

            messages.innerHTML +=  "<li>" + e.data + "</li>"

            if( e.data == "finish" )
            {
                es.close()
                log.innerHTML = "We have processed your request successfully"
            }

        }

        es.onerror = e =>
        {
            log.innerHTML = "The connection has closed"
        }

    })
    
</script>

</body>
</html>

We can use PHP built in server, and start it in this manner:

php -S localhost:9090

<?php

header("Access-Control-Allow-Origin: *");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

function run()
{

    yield "Process the database";
    sleep(2);

    yield "Sending an Email";
    sleep(2);

    yield "Doing another long Process";
    sleep(5);

    yield "finish";
    
}

function encode( $data )
{
    return "data:" . $data . "\n\n";
}

$gen = run();

while( $gen->valid() )
{
    echo encode( $gen->current() );
    ob_flush();
    flush();
    $gen->next();    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment