Peter
Peter

Reputation: 9123

Killing a PHP script that's using ignore_user_abort()

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.

Upvotes: 2

Views: 2191

Answers (2)

StackSlave
StackSlave

Reputation: 10627

ignore_user_abort() has to do with halting the execution of the current PHP page when the Client (Browser User) closes their Browser. It will not stop your PHP code from executing. Therefore die; under a condition or changing the set_time_limit() can kill your PHP script.

Your code may look something like:

set_time_limit(200); ignore_user_abort(1);
include 'connection.php'; $db = db();
// do queries like normal not in a continuous loop
if($q = $db->query(/**/)){
  if($q->num_rows > 0){
    // do stuff
  }
}
else{
  die;
}

Upvotes: 1

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

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.

Upvotes: 3

Related Questions