您将需要添加“ignore_user_abort(true);” 在 PHP 脚本之上,并在从脚本中回显某些内容后调用“ob_flush()”(有关原因,请参见PHP flush() 手册页)。工作示例(概念证明):
<?php
ignore_user_abort(true);
function log_message($s, $ss) {
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $s . ": " . $ss . "\n";
fwrite($fh, $stringData);
fclose($fh);
}
for ($i=0;$i<5;$i++) {
echo "<br>";
//flush();
ob_flush();
if (connection_aborted()) {
log_message('error1', connection_status());
exit;
}
else {
log_message('error2', connection_status());
}
sleep(1);
}
PS connection_status() 如果连接仍然处于活动状态,则返回 0,如果连接已关闭,则返回 1。
编辑:
我的错。调用 flush() 和 ob_flush() (请阅读 flush() 手册页、上面的链接以及本主题的答案),否则可能无法正常工作,具体取决于服务器/php 配置。以下代码在 WAMP 上使用 PHP 5.3.8 进行了测试(无需调用 flush()),现在在 Ubuntu 上使用 PHP 5.3.10 进行了测试。在 ob_flush() 之前调用 flush() 是必要的。
完整的测试代码:
索引.html:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "script.php",
context: document.body
}).done(function(data) {
alert(data);
});
})
</script>
</head>
<body>
</body>
</html>
脚本.php:
ignore_user_abort(true);
function log_message($type, $message, $file = 'log.txt') {
$fh = fopen($file, 'a') or die("can't open file");
$conn_status = connection_status();
if($conn_status === CONNECTION_NORMAL) {
$status = 'normal';
} elseif($conn_status === CONNECTION_ABORTED) {
$status = 'aborted';
} else {
$status = 'timeout';
}
$aborted = connection_aborted() ? 'yes' : 'no';
$data = $type . ': ' . $message . "\n";
$data .= 'Connection status: ' . $status . "\n";
$data .= 'Aborted: ' . $aborted . "\n\n\n";
fwrite($fh, $data);
fclose($fh);
}
for ($i = 0; $i < 10; $i++) {
echo "<br>";
flush();
ob_flush();
if (connection_aborted()) {
log_message('Error', 'Connection closed by user!');
exit;
}
else {
log_message('Info', 'Everything is fine. Move along...');
}
sleep(1);
}
调用 index.html 页面并关闭选项卡或整个浏览器后,您应该在 log.txt 文件中看到下一个信息:
Info: Everything is fine. Move along...
Connection status: normal
Aborted: no
Info: Everything is fine. Move along...
Connection status: normal
Aborted: no
Info: Everything is fine. Move along...
Connection status: normal
Aborted: no
Error: Connection closed by user!
Connection status: aborted
Aborted: yes