特点
在线手册:中文 英文
PHP手册

连接处理

在 PHP 内部,系统维护着连接状态,其状态有三种可能的情况:

当 PHP 脚本正常地运行 NORMAL 状态时,连接为有效。当远程客户端中断连接时,ABORTED 状态的标记将会被打开。远程客户端连接的中断通常是由用户点击 STOP 按钮导致的。当连接时间超过 PHP 的时限(请参阅 set_time_limit() 函数)时,TIMEOUT 状态的标记将被打开。

可以决定脚本是否需要在客户端中断连接时退出。有时候让脚本完整地运行会带来很多方便,即使没有远程浏览器接受脚本的输出。默认的情况是当远程客户端连接中断时脚本将会退出。该处理过程可由 php.ini 的 ignore_user_abort 或由 httpd.conf 设置中对应的“php_value ignore_user_abort”以及 ignore_user_abort() 函数来控制。如果没有告诉 PHP 忽略用户的中断,脚本将会被中断,除非通过 register_shutdown_function() 设置了关闭触发函数。通过该关闭触发函数,当远程用户点击 STOP 按钮后,脚本再次尝试输出数据时,PHP 将会检测到连接已被中断,并调用关闭触发函数。

脚本也有可能被内置的脚本计时器中断。默认的超时限制为 30 秒。这个值可以通过设置 php.inimax_execution_timehttpd.conf 设置中对应的“php_value max_execution_time”参数或者 set_time_limit() 函数来更改。当计数器超时的时候,脚本将会类似于以上连接中断的情况退出,先前被注册过的关闭触发函数也将在这时被执行。在该关闭触发函数中,可以通过调用 connection_status() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用,该函数将返回 2。

需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制,脚本将被退出,设置过的关闭触发函数也将被执行。在这时会发现函数 connection_status() 返回 3。


特点
在线手册:中文 英文
PHP手册
PHP手册 - N: 连接处理

用户评论:

scragar at gmail dot com (22-Mar-2012 10:12)

tom lgold2003 at gmail dot com noted that there was some strange behaviour for him flushing the buffers.

The behaviour is not strange, there are multiple buffers:

<?php // start of the page, first buffer is normally enabled here

ob_start();// this starts the second

echo "test";// Write some content to buffer two

ob_end_flush();// This closes buffer two and begins writting to buffer one.

flush();// This outputs buffer one to the screen.

?>

If you want to avoid this use a loop to close all the buffers:

<?php
// One by default

ob_start();// two

ob_start();// three

// This closes each buffer until it fails,
// probably because there are no more buffers left.
while( @ob_end_flush() );

?>

Anonymous (30-Dec-2011 01:52)

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();
}
?>

pgl at yoyo dot org (22-Jun-2011 11:09)

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
?>

a1n2ton at gmail dot com (12-Dec-2009 09:09)

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();
?>

tom lgold2003 at gmail dot com (10-Sep-2009 07:43)

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
?>

alan at burrist dot co dot uk (25-Feb-2009 12:57)

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

fanfear at yahoo dot com (05-Jan-2009 09:59)

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;
    }
?>

Jean Charles MAMMANA (01-Apr-2008 09:25)

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...

Anonymous (13-Nov-2007 10:06)

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();

arr1 at hotmail dot co dot uk (14-Nov-2006 07:51)

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

bg at ms dot com (22-Sep-2005 02: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 07: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 11: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 01: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 (07-Aug-2003 07: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.