Работа с соединениями

Замечание: Вся последующая информация применима к версиям 3.0.7 и выше.

Статус соединения сохраняется внутренними механизмами PHP. Ниже перечислены три возможные состояния:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT

Во время штатного выполнения PHP-скрипта установлен статус NORMAL. В случае, если удаленный клиент разорвал соединение, статус изменяется на ABORTED. Чаще всего отсоединение удаленного клиента происходит при нажатии кнопки "Stop" в браузере. В случае, если достигается установленный временной лимит (ознакомьтесь с функцией set_time_limit()), будет установлен статус TIMEOUT.

Вы можете решать, приводит ли отключение клиента к завершению вашего скрипта. Иногда бывает необходимо, чтобы скрипт выполнился до конца, даже если отсутствует удаленный браузер, которому адресован весь вывод. По умолчанию скрипт завершает свою работу при отключении клиента. Это поведение может быть изменено при помощи опции ignore_user_abort в конфигурационном файле php.ini. Такого же результата можно добиться, указав "php_value ignore_user_abort" в конфигурационном файле Apache или воспользовавшись функцией ignore_user_abort(). Если вы явно не указали на необходимость игнорировать разрыв соединения с клиентом, выполнение скрипта будет прервано. Исключением является тот случай, если используя register_shutdown_function(), вы указали специальную функцию, вызываемую при завершении скрипта. В таком случае после того, как пользователь нажал кнопку "Stop" в своем браузере, при первой же попытке что-либо вывести PHP обнаруживает, что соединение с клиентом было утеряно, и вызывает завершающую функцию. Эта функция также вызывается при нормальном завершении работы вашего скрипта, поэтому для того, чтобы выполнить некоторые специфические действия при отсоединении клиента, вам понадобится функция connection_aborted(), которая возвращает TRUE, если соединение было разорвано.

Выполнение вашего скрипта также может быть прервано встроенным таймером. Стандартное ограничение по времени составляет 30 секунд, изменить его можно при помощи директивы max_execution_time в конфигурационном файле php.ini. Такого же результата можно достичь, добавив php_value max_execution_time в конфигурационный файл Apache или воспользовавщись функцией set_time_limit(). При достижении скриптом временного лимита выполнение скрипта прерывается и вызывается завершающая функция, если она была указана. Уточнить причину завершения скрипта вы можете при помощи функции connection_timeout(), которая возвращает TRUE, если скрипт был прерван по достижению временного ограничения.

Единственное, что следует заметить - что оба статуса: ABORTED и TIMEOUT,- могут быть установлены одновременно. Это может произойти в том случае, если вы явно указали необходимость игнорировать отсоединение удаленного клиента. В таком случае после разрыва соединения, отметив этот факт, PHP продолжит выполнение скрипта, и при достижении временного лимита будет вызвана завершающая функция, если таковая была указана. В этой точке вы можете обнаружить, что и connection_timeout(), и connection_aborted() возвращают TRUE. Вы также можете проверить оба статуса одновременно, вызвав функцию connection_status(), которая возвращает битовые значения для активных статусов. В случае, если оба статуса активны, она, к примеру, вернет значение 3.

Коментарии

These functions are very useful for example if you need to control when a visitor in your website place an order and you need to check if he/she didn't clicked the submit button twice or cancelled the submit just after have clicked the submit button. 
If your visitor click the stop button just after have submitted it, your script may stop in the middle of the process of registering the products and do not finish the list, generating inconsistency in your database.
With the ignore_user_abort() function you can make your script finish everything fine and after you can check with register_shutdown_function() and connection_aborted() if the visitor cancelled the submission or lost his/her connection. If he/she did, you can set the order as not confirmed and when the visitor came back, you can present the old order again.
To prevent a double click of the submit button, you can disable it with javascript or in your script you can set a flag for that order, which will be recorded into the database. Before accept a new submission, the script will check if the same order was not placed before and reject it. This will work fine, as the script have finished the job before.
Note that if you use ob_start("callback_function") in the begin of your script, you can specify a callback function that will act like the shutdown function when our script ends and also will let you to work on the generated page before send it to the visitor.
2003-08-07 02:32:35
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Автор:
The point mentioned in the last comment isn't always the case.

If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.

I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB.

So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.
2004-09-18 06:16:57
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.

sts at mail dot xubion dot hu
Posted the original solution:

<?php
header
("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

Which works fine until you substitute phpinfo() for 
echo ('text I want user to see'); in which case the headers are never sent!

The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.

example:

<?php
 ob_end_clean
();
 
header("Connection: close");
 
ignore_user_abort(); // optional
 
ob_start();
 echo (
'Text the user will see');
 
$size ob_get_length();
 
header("Content-Length: $size");
 
ob_end_flush(); // Strange behaviour, will not work
 
flush();            // Unless both are called !
 // Do processing here 
 
sleep(30);
 echo(
'Text user will never see');
?>
 
Just spent 3 hours trying to figure this one out, hope it helps someone :)

Tested in:
IE 7.5730.11
Mozilla Firefox 1.81
2006-11-14 13:51:47
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Автор:
in regards of posting from:
arr1 at hotmail dot co dot uk

if you use/write sessions you need to do this before:
(otherwise it does not work)

session_write_close();

and if wanted:

ignore_user_abort(TRUE);
instead of ignore_user_abort();
2007-11-13 04:06:10
http://php5.kiev.ua/manual/ru/features.connection-handling.html
connection_status() return ABORTED state ONLY if the client disconnects gracefully (with STOP button). In this case the browser send the RST TCP packet that notify PHP the connection is closed.
But.... If the connection is stopped by networs troubles (wifi link down by exemple) the script doesn't know that the client is disconnected :(

I've tried to use fopen("php://output") with stream_select() on writting to detect write locks (due to full buffer) but php give me this error : "cannot represent a stream of type Output as a select()able descriptor"

So I don't know how to detect correctly network trouble connection...
2008-04-01 16:25:45
http://php5.kiev.ua/manual/ru/features.connection-handling.html
hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.

When using the codes, it nearly drive me mad and I found another thing that may affect the codes:

Content-Encoding: gzip

This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.

So, it may need to send the header to prevent this problem.

now, the code becomes:

<?php
ob_end_clean
();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
ignore_user_abort(true); // optional
ob_start();
echo (
'Text user will see');
$size ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Strange behaviour, will not work
flush();            // Unless both are called !
ob_end_clean();

//do processing here
sleep(5);

echo(
'Text user will never see');
//do some processing
?>
2009-09-10 02:43:21
http://php5.kiev.ua/manual/ru/features.connection-handling.html
PHP changes directory on connection abort so code like this will not do what you want:

<?php
function abort()
{
     if(
connection_aborted())
           
unlink('file.ini');
}
register_shutdown_function('abort');
?>

actually it will delete file in apaches's root dir so if you want to unlink file in your script's dir on abort or write to it you have to store directory
<?php
function abort()
{
     global 
$dsd;
     if(
connection_aborted())
           
unlink($dsd.'/file.ini');
}
register_shutdown_function('abort');
$dsd=getcwd();
?>
2009-12-12 15:09:44
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Автор:
This simple function outputs a string and closes the connection. It considers compression using "ob_gzhandler"

It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn't work.

<?php
function outputStringAndCloseConnection2($stringToOutput)
{   
   
set_time_limit(0);
   
ignore_user_abort(true);   
   
// buffer all upcoming output - make sure we care about compression:
   
if(!ob_start("ob_gzhandler"))
       
ob_start();         
    echo 
$stringToOutput;   
   
// get the size of the output
   
$size ob_get_length();   
   
// send headers to tell the browser to close the connection   
   
header("Content-Length: $size");
   
header('Connection: close');   
   
// flush all output
   
ob_end_flush();
   
ob_flush();
   
flush();   
   
// close current session
   
if (session_id()) session_write_close();
}
?>
2011-12-29 19:52:19
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Автор:
I was quite stuck when trying to make my script redirect the client to another URL and then continue processing. The reason was php-fpm. All possible buffer flushes did not work, unless I called fastcgi_finish_request();

For example:

<?php
   
// redirecting...
   
ignore_user_abort(true);
   
header("Location: ".$redirectUrltrue);
   
header("Connection: close"true);
   
header("Content-Length: 0"true);
   
ob_end_flush();
   
flush();
   
fastcgi_finish_request(); // important when using php-fpm!
   
   
sleep (5); // User won't feel this sleep because he'll already be away
   
    // do some work after user has been redirected
?>
2012-09-27 21:25:55
http://php5.kiev.ua/manual/ru/features.connection-handling.html
I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing.

I finally found out what was wrong:
The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished.

Solution:
Close the session manually when redirecting using session_write_close():

<?php
ignore_user_abort
(true);
set_time_limit(0);

$strURL "PUT YOUR REDIRCT HERE";
header("Location: $strURL"true);
header("Connection: close"true);
header("Content-Encoding: none\r\n");
header("Content-Length: 0"true);

flush();
ob_flush();

session_write_close();

// Continue processing...

sleep(100);
exit;
?>

But careful:
Make sure that your script doesn't write to the session after session_write_close(), i.e. in your background processing code.  That won't work.  Also avoid reading, remember, the next script may already have modified the data.

So try to read out the data you need prior to redirecting.
2013-07-29 17:38:53
http://php5.kiev.ua/manual/ru/features.connection-handling.html
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
/*
 * Anti-Pattern
 */
 
# Connect
mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
 
# Choose a database
mysql_select_db('someDatabase') or die('Could not select database');
 
# Perform database query
$query = "SELECT * from someTable";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
 
# Filter through rows and echo desired information
while ($row = mysql_fetch_object($result)) {
    echo $row->name;
}
2016-04-14 16:54:23
http://php5.kiev.ua/manual/ru/features.connection-handling.html
Автор:
The CONNECTION_XXX constants that are not listed here for some reason are:

0 = CONNECTION_NORMAL
1 = CONNECTION_ABORTED
2 = CONNECTION_TIMEOUT
3 = CONNECTION_ABORTED & CONNECTION_TIMEOUT

Number 3 is effectively tested like this:
if (CONNECTION_ABORTED & CONNECTION_TIMEOUT)
    echo 'Connection both aborted and timed out';
2017-03-08 07:58:16
http://php5.kiev.ua/manual/ru/features.connection-handling.html

    Поддержать сайт на родительском проекте КГБ