Глава 40. Работа с соединениями

Замечание: Вся последующая информация применима к версиям 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.



Работа с соединениями
bg at ms dot com
22-Sep-2005 06:42
Confirmed.  User presses STOP button.  This sends a RST packet and closes the connection.  PHP is most certainly immediately affected (i.e., the script is stopped, whether or not any output is pending for the user, or even if script is just grinding away on a database without having output anything).

ignore_user_abort() exists to prevent this.

If user STOPS, script ignores the RST and runs to completion (the output is apparently ignored by apache and not sent to the user, who sent the RST and closed the TCP connection).  If user's connection just vanishes (isp problem, disconnect, whatever), and there is no RST sent by user, then eventually the script will timeout.
hrgan at melibado dot com
12-Dec-2004 11:08
As it was said, connection handling is very useful when web application need to do something in background. I found it very useful when application need something from database, wrap that data with template, create some html files and save it to filesystem. And all that on server with heavy load. Without connection handling - function ignore_user_abort() - this process can be interrupted by user and final step will never be done.
Lee
18-Sep-2004 03:16
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.
ej at campbell *dot* name
12-Feb-2004 05:01
I don't think the first example given below will occur in the real world.

As long as your order handling script does not output anything, there's no way that it will be aborted before it completes processing (unless it timeouts). PHP only senses user aborts when a script sends output. If there's no output sent to the client before processing completes, which is presumably the case for an order handling script, the script will run to completion.

So, the only time a script can be terminated due to the user hitting stop is when it sends output. If you don't send any output until processing completes, you don't have to worry about user aborts.
pulstar at mail dot com
06-Aug-2003 11:32
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.

<Работа с удаленными файламиПостоянные соединения с базами данных>
 Last updated: Mon, 14 Nov 2005