connection_aborted in PHP

Syntax of connection_aborted

int connection_aborted()

Returns true (1) if the client disconnected (for example, clicked Stop in the browser) at any point before the function is called. Returns false (0) if the client is still connected

Example of connection_aborted

<?php
ignore_user_abort(true);
header('Transfer-Encoding:chunked');
ob_flush();
flush();
$start = microtime(true);
$i = 0;
// Use this function to echo anything to the browser.
function vPrint($data){
    if(strlen($data))
        echo dechex(strlen($data)), "\r\n", $data, "\r\n";
    ob_flush();
    flush();
}
// You MUST execute this function after you are done streaming information to the browser.
function endPacket(){
    echo "0\r\n\r\n";
    ob_flush();
    flush();
}
do{
    echo "0";
    ob_flush();
    flush();
    if(connection_aborted()){
        // This happens when connection is closed
        file_put_contents('/tmp/test.tmp', sprintf("Conn Closed\nTime spent with connection open: %01.5f sec\nLoop itterations: %s\n\n", microtime(true) - $start, $i), FILE_APPEND);
        endPacket();
        exit;
    }
    usleep(50000);
    vPrint("I get echo'ed every itteration (every .5 second)<br />\n");
}while($i++ < 200);
endPacket();
?>

Leave a Comment