A trick to detecting if a connection is closed without having to send data that will otherwise corrupt the stream of data (like a binary file) you can use a combination of chunking the data on HTTP/1.1 by sending a "0" ("zero") as a leading chunk size without anything else.
*NOTE* it's important to note that it's not a good idea to check the stream more then once every few seconds. By doing this you are potentially increasing the data sent to the user with no gain to the user.
A good reason to do it this way is if you are generating a report that takes a long time to run and takes a lot of server resources. This would allow the server to detect if a user canceled the download and do any cleanup without corrupting the file file being download.
Here is an example:
<?php
ignore_user_abort(true);
header('Transfer-Encoding:chunked');
ob_flush();
flush();
$start = microtime(true);
$i = 0;
// Use this function to echo anything to the browser.
function vPrint($data){
if(strlen($data))
echo dechex(strlen($data)), "\r\n", $data, "\r\n";
ob_flush();
flush();
}
// You MUST execute this function after you are done streaming information to the browser.
function endPacket(){
echo "0\r\n\r\n";
ob_flush();
flush();
}
do{
echo "0";
ob_flush();
flush();
if(connection_aborted()){
// This happens when connection is closed
file_put_contents('/tmp/test.tmp', sprintf("Conn Closed\nTime spent with connection open: %01.5f sec\nLoop itterations: %s\n\n", microtime(true) - $start, $i), FILE_APPEND);
endPacket();
exit;
}
usleep(50000);
vPrint("I get echo'ed every itteration (every .5 second)<br />\n");
}while($i++ < 200);
endPacket();
?>
PHP.mk документација
connection_aborted
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
function.connection-aborted.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
function.connection-aborted.php
connection_aborted
Референца за `function.connection-aborted.php` со подобрена типографија и навигација.
connection_aborted
(PHP 4, PHP 5, PHP 7, PHP 8)
connection_aborted — Провери дали клиентот се исклучил
Параметри
Оваа функција нема параметри.
Вратени вредности
Враќа 1 ако клиентот се исклучил, 0 инаку.
Види Исто така
- connection_status() - Проверете дали клиентот е исклучен
- ignore_user_abort() - Постави дали исклучувањето на клиентот треба да го прекине извршувањето на скриптата
- - Враќа битно поле за статус на врската Ракување со врски
Белешки од корисници 2 забелешки
nathanb at php dot net ¶
пред 13 години
Рупак Бајгаин ¶
пред 2 години
One trick i used uas to send values in comment to get long pooling with disconnect check
Like for json:
Send 0 and flush before connection aborted.
Eg. {"x":"000000
And after result is ready send ", and json after removing 1st {
So it looks like
{"x":"00000000000","y":"result","z":"result2"}