Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a PHP script that's using ignore_user_abort()

Tags:

php

Some time ago, I was looking for a method to keep a PHP script running when the user aborted. (When the user closed it's browser). I needed this for some long queries to complete even if the user decided to leave.

ignore_user_abort(1);
set_time_limit(0);

while (true) {
    // Do queries
}

How would I kill the above script?

Update

The getmypid() function has been suggested to me. I now implemented the following:

ignore_user_abort(1);
set_time_limit(0);

// Get process id
$pid = getmypid();

$stmt = "INSERT INTO processes (pid, started) VALUES ('".$pid."', NOW())";
while (true) {
    // Do Queries
    if ($query) {
        break;
    }
}
$stmt = "UPDATE processes SET ended=NOW() WHERE pid='".$pid."'";

I can now query the database to see hwat processes have not finished yet. I'll know that these processes are stuck.

like image 375
Peter Avatar asked Apr 11 '26 19:04

Peter


1 Answers

You can kill the php process by identifying the process ids. but that you have to execute directly from terminal by logged in as a root user. Its a bad approach to give privilege for the www-data(php user) to kill the process.

Best approach is, Inside the loop you have to check any flag stored in database in order to proceed, otherwise exit. So you can easily manage those database flag easily through code.

like image 52
Sanjay Kumar N S Avatar answered Apr 14 '26 09:04

Sanjay Kumar N S



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!