PHP:使用POST / AJAX取消运行脚本?

时间:2012-04-11 17:00:28

标签: php jquery process

我的php脚本使用php simplehtmldom解析html并获取我想要的所有链接和图像,这可以运行一段时间,具体取决于要下载的图像数量。

我认为在这种情况下允许取消是个好主意。目前我使用Jquery-Ajax调用我的php,我能找到的最接近的是php register_shutdown_function,但不确定它是否适用于我的情况。有什么想法吗?

所以一旦启动php,它就不会被打扰?像fire ajax再次调用退出到同一个php文件?

1 个答案:

答案 0 :(得分:1)

只有在通过AJAX处理真正大量的数据加载时,这才是好的。对于其他情况,只需在JS中处理它就不会在取消时显示结果。

但正如我所说的如果您正在处理大量数据,那么您可以在运行脚本的每个第n步中添加一个中断条件,并使用另一个脚本来满足该条件。例如,您可以使用文件存储中断数据或MySQL MEMORY表。

实施例

1,process.php(ajax脚本处理数据加载)

// clean up previous potential interrupt flag
$fileHandler = fopen('interrupt_condition.txt', 'w+');
fwrite($fileHandler, '0');
fclose($fileHandler);

function interrupt_check() {
   $interruptfile = file('interrupt_condition.txt');
   if (trim($interruptfile[0]) == "1") {    // read first line, trim it and parse value - if value == 1 interrupt script
      echo json_encode("interrupted" => 1);
      die();
   }
}

$i = 0;
foreach ($huge_load_of_data as $object) {
   $i++;
   if ($i % 10 == 0) { // check for interrupt condition every 10th record
      interrupt_check();
   }

   // your processing code
}
interrupt_check(); // check for last time (if something changed while processing the last 10 entries)

2,interrupt_process.php(将取消事件传播到文件的ajax脚本)

$fileHandler = fopen('interrupt_condition.txt', 'w+');
fwrite($fileHandler, '1');
fclose($fileHandler);

这肯定会影响脚本的性能,但会让你成为关闭执行的后门。这是一个非常简单的示例 - 您需要使其更复杂,以使其同时适用于更多用户等。

您还可以使用 MySQL MEMORY表 MEMCACHE - 非持久性缓存服务器或您可以找到的任何非持久性存储。