Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP connection_aborted() does not work when page changes

Tags:

php

I'm trying to serve an image while adding a MySQL row for each second the image was viewed.

I'm serving it in chunks of 1024 bits (total size is of image is 20kb)

The problem is that if I load the page where the image is displayed and then close the window or click a link that takes me to a different page the script keeps running and does not die as it should.

ignore_user_abort(false);
$file = 'a.jpg';
header('Content-Type: image/jpeg');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();

$conn = mysql_connect("localhost","user","pass");
mysql_select_db("mydb",$conn);

$fp=fopen($file,"rb");
$i=0;

while (!feof($fp)) {

    print(fread($fp,1024));
    sleep(1);
    mysql_query("INSERT INTO table (VIEWTIME) VALUES ('$i')");
    $i++;
    flush();
    ob_flush();
    if (connection_aborted()) {
        die();
    }
}

I'm trying to find a 'server-side' only solution since I have some technical restrictions that prevents me from using any JS or any client side languages.

like image 513
user838437 Avatar asked Jan 17 '26 17:01

user838437


1 Answers

Perhaps

ignore_user_abort(false);

Should be

ignore_user_abort(true);

Docs

like image 124
Toby Allen Avatar answered Jan 20 '26 09:01

Toby Allen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!