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: ".$redirectUrl, true);
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
?>
接続処理
PHP 内部で、接続ステータスが保持されます。 これは、次の 3 つの状態をとりえます。
- 0 - NORMAL
- 1 - ABORTED
- 2 - TIMEOUT
通常 PHP が実行されている場合、NORMAL 状態がアクティブになります。 リモートクライアントが接続を切った場合、ABORTED 状態フラグが有効になります。 通常、リモートクライアントの接続断は、STOP ボタンを押すことにより発生します。 PHP 側の時間制限 ( set_time_limit() 参照) にかかった場合、 TIMEOUT 状態フラグが有効になります。
スクリプトを終了させるためにクライアントとの接続を切断するかどうかを
決めることが出来ます。
時々、出力がどのリモートブラウザにも受信されない場合でも、
常にスクリプトの実行完了まで実行する方が便利であることがあります。
しかし、デフォルトの動作はリモートクライアントとの接続が断となった際にスクリプト
の実行は破棄されます。
この動作は、php.ini ディレクティブ ignore_user_abort にて
設定できます。
同様に同じ意味を有する Apache httpd.conf ディレクティブ
php_value ignore_user_abort または
ignore_user_abort() 関数にて設定することも可能です。
PHP にユーザーによる破棄を無視するように設定していない場合、
ユーザーが破棄した場合、スクリプトの実行は終了します。
一つの例外は、 register_shutdown_function() を用いて
シャットダウン関数を定義した場合です。
シャットダウン関数を定義した場合、リモートユーザーが STOP ボタンを押した後、
次にスクリプトが何か出力を行おうとした場合、PHP は接続が破棄されたことを検知し、
シャットダウン関数がコールされます。
このシャットダウン関数は、スクリプトが正常に終了した
際にもコールされます。
このため、クライアントが接続を切断した場合に別の動作をさせたい場合に
は、 connection_aborted() 関数を使用することが
可能です。
この関数は、接続が破棄された場合に、TRUE を返します。
スクリプトは、組み込みのスクリプトタイマーによっても終了することが できます。デフォルトのタイムアウトは、30 秒です。 これは、php.iniディレクティブ max_execution_time または同義の Apache httpd.conf ディレクティブ php_value max_execution_time を set_time_limit() 関数と同様に用いることにより 変更することが可能です。タイマーが切れた時、スクリプトは中断されます。 上記のクライアントが接続を切るケースのように シャットダウン関数が登録されている場合、この関数がコールされます。 このシャットダウン関数の中では、 connection_status() 関数のコールにより タイムアウトがシャットダウン関数のコールを生じさせるかどうかを 確認することができます。 この関数は、タイムアウトによりシャットダウン関数がコールされた 場合に 2 を返します。
もう一つ注意すべき点は、状態 ABORTED および TIMEOUT は同時にアクティブにできるということです。 これは、PHP をユーザーによる中断を無視するよう設定した場合に 可能です。 PHP は、ユーザーが接続を破棄しているが、スクリプトは 実行しつづけるということがある可能性があることに注意する 必要があります。 時間制限にかかって中断される場合、もしあればシャットダウン関数が コールされます。 ここで、 connection_status() は 3 を返します。
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();
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.
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.
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...
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();
?>
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
If you just want a script that will instantly disconnect the browser and then continue processing, this seems to work:
<?php
header("Content-Length: 0");
header("Connection: close");
flush();
// browser should disconnect at this point
?>
Even with ob_flush() and flush(), PHP may be unable to detect the connection status change due to *a firewall on client's machine*.
Consider a browser receiving the output of a script. The script regularly outputs something innocent, like "<br>".
a) The Stop button is pressed. The browser instructs to close the connection gracefully, TCP/IP stack exchanges those final FIN and ACK packets, and the server knows that the client went away.
b) The entire browser is killed. The client's stack sees that nobody is using the socket, so the next data packet from server will be answered with a TCP RST, and the server immediately knows there is no client.
But, a stealth firewall is designed to block those RST messages as well. The server's stack will only see absence of ACK replies, and therefore will occasionally retransmit the entire bunch of accumulated data. Only after a certain number of retransmission failures, this will be considered a connection loss and propagated up to PHP.
In my case, turning off the Comodo Firewall at the client changed the situation immediately.
if you are using fcgid on apache and are having trouble getting post processing to work, set FcgidOutputBufferSize 0 in apache config and sleep(1) in your php script before doing the post processing.
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
?>
A simple but useful packaging of arr1's suggestion for continuing processing after telling the the browser that output is finished.
I always redirect when a request requires some processing (so we don't do it twice on refresh) which makes things easy...
<?php
function redirect_and_continue($sURL)
{
header( "Location: ".$sURL ) ;
ob_end_clean(); //arr1s code
header("Connection: close");
ignore_user_abort();
ob_start();
header("Content-Length: 0");
ob_end_flush();
flush(); // end arr1s code
session_write_close(); // as pointed out by Anonymous
}
?>
Of course this won't work if the output has started - but the a simple redirect wouldn't work anyway.
UPDATE: To get this to work on IIS 7 you need to switch off IIS output buffering by adding responseBufferLimit="0" to the relevant handler in your web.config
Thanks for the tip arr1
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.
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.
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.
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();
}
?>
i use this code when i want php infinite loop
<?php
set_time_limit (0);//run script forever
ignore_user_abort ();//run script in background
$i = 0;
echo "start\n";
while (1) {
$i++;
echo $i, "\n";
$sleep = sleep (3);
if ($sleep == 0 or $sleep or $sleep == FALSE) continue;
if (connection_aborted ()) continue;
if (connection_status () != 0) continue;
}
?>
