PHP - 强制连接关闭时没有数据发送

时间:2014-11-20 12:48:32

标签: php browser

我有一个通过ajax调用的脚本。该脚本在Apache 2.4.7服务器和PHP 5.5.9上运行。

脚本向浏览器发回响应,然后关闭连接并继续执行更多操作。

这是第一种方法。它不起作用。

<?php
ob_start();
echo "some text";
$size = ob_get_length();
ignore_user_abort(true);
header("Connection: close\r\n");
header("Content-Length: $size");
header("Content-Encoding: None", true);
ob_end_flush();     
flush(); 
ob_end_clean(); 
//after this a few actions follow
?>

错误是:

  • cURL:(18)转移关闭,剩余9个字节读取
  • browser:net :: ERR_CONTENT_LENGTH_MISMATCH

这是第二种方法。它有效。

<?php
ob_start();
echo "some text";
$data = ob_get_contents();
$size = ob_get_length();
ob_end_clean(); 
ignore_user_abort(true);
header("Connection: close\r\n");
header("Content-Length: $size");
header("Content-Encoding: None", true);
echo $data;
ob_end_flush();     
flush(); 
ob_end_clean(); 
//after this a few actions follow
?>

这是通过反复试验建立的,我不知道为什么一个有效,另一个没有。

我希望你能帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

看起来问题是你的最后三行:

ob_end_flush();     
flush(); 
ob_end_clean(); 

ob_end_flush()ob_end_clean()都关闭了输出缓冲。

根据php's ob_start()

  

要输出存储在内部缓冲区中的内容,请使用ob_end_flush()。或者,ob_end_clean()将静默地丢弃缓冲区内容。

两者的组合正在消除你的输出。

当我将其更改为:

时,我可以让您的第一个代码段正常工作
ob_start();
echo "some text";
$size = ob_get_length();
ignore_user_abort(true);
header("Connection: close\r\n");
header("Content-Length: $size");
header("Content-Encoding: None", true);
ob_flush();
ob_end_clean();