Question

how i can know in my php code when a data transfer is closed by the client ?

i have found this code (bellow) on stackoverflow but i want to write a text into a file when the client close him window...

<?php
        header('Content-Encoding', 'chunked');
        header('Transfer-Encoding', 'chunked');
        header('Content-Type', 'text/html');
        header('Connection', 'keep-alive');

        ob_flush();
        flush();

        $p = "";  //padding
        for ($i=0; $i < 1024; $i++) { 
            $p .= " ";
        };
        echo $p;

        ob_flush();
        flush();

        for ($i = 0; $i < 10000; $i++) {
            echo "string";
            ob_flush();
            flush();
            sleep(2);
        }

?>
Was it helpful?

Solution

By calling connection_aborted() you can find out if the client is still connected or not. This could be done within your for loop like below.

Also you will need to tell PHP to continue execution after the client disconnects by calling ignore_user_abort(). If you don't do that, your script will terminate as soon as the client disconnects. Depending on your PHP config, you may also need to set a larger or unlimited time limit using set_time_limit().

ignore_user_abort(true);

for ($i = 0; $i < 10000; $i++) {

     if(connection_aborted()){
         // client disconnected, write to file here
     }

     echo "string";
     ob_flush();
     flush();
     sleep(2);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top