dongpeng7744
2015-11-17 07:40 阅读 45
已采纳

杀死使用ignore_user_abort()的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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douyi5157 douyi5157 2015-11-17 07:51

    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.

    点赞 评论 复制链接分享
  • douying8666 douying8666 2015-11-17 07:52

    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;
    }
    
    点赞 评论 复制链接分享

相关推荐