PHP Doku:: Verbindungssteuerung - features.connection-handling.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFeaturesVerbindungssteuerung

Ein Service von Reinhard Neidl - Webprogrammierung.

Features

<<Zugriff auf entfernte Dateien

Persistente Datenbankverbindungen>>

Verbindungssteuerung

PHP erhält intern einen Verbindungsstatus. Dieser kann drei Zustände annehmen:

Wenn ein PHP-Skript aktiv ist, ist der Status üblicherweise NORMAL. Sollte der Client-Rechner die Verbindung beenden, wird der Status auf ABORTED gesetzt. Ein clientseitiges Beenden der Verbindung wird für gewöhnlich veranlasst, wenn der Benutzer den STOP-Button seines Browsers drückt. Wenn das eingestellte Zeitlimit (siehe set_time_limit()) überschritten wird, wird der Status TIMEOUT gesetzt.

Sie können entscheiden, ob der Verbindungsabbruch seitens des Clients den Abbruch des Skriptes zur Folge haben soll. Manchmal ist es sinnvoll, Skripte sauber zu beenden, auch wenn kein Browser mehr zur Verfügung steht, der die Ausgabe empfängt. Die Abarbeitung eines Skriptes wird standardmäßig abgebrochen, wenn der Client die Verbindung beendet. Dieses Verhalten kann sowohl durch die Option ignore_user_abort in der Konfigurationsdatei php.ini, durch die entsprechende Option php_value ignore_user_abort in der Apache-Konfigurationsdatei httpd.conf als auch durch ignore_user_abort() beeinflußt werden. Wenn PHP nicht angewiesen wird, einen Verbindungsabbruch durch den Benutzer zu ignorieren und die Verbindung dann durch den Benutzer beendet wird, wird die Abarbeitung des Scriptes abgebrochen. Die einzige Ausnahme ist, wenn durch die Funktion register_shutdown_function() eine Shutdown-Funktion angegeben wird, die bei clientseitigem Abbruch ausgeführt wird. Wenn dann der Benutzer den STOP-Button seines Browsers drückt, wird PHP bei der nächsten Ausgabe des Skriptes feststellen, dass die Verbindung abgebrochen wurde und die Shutdown-Funktion aufrufen. Diese Shutdown-Funktion wird auch aufgerufen, wenn das Skript auf normalem Wege beendet wird, daher sollte man, wenn man für den Fall eines Benutzerabbruchs etwas anderes vorgesehen hat, die Funktion connection_aborted() verwenden. Sie gibt TRUE zurück, wenn die Verbindung abgebrochen wurde.

Ein Skript kann ebenfalls durch den eingebauten Script-Timer beendet werden. Der Standard-Timeout beträgt 30 Sekunden. Er kann durch die Option max_execution_time in der php.ini, durch den entsprechenden Eintrag php_value max_execution_time in der Apache-Konfigurationsdatei httpd.conf oder durch die Funktion set_time_limit() beeinflußt werden. Bei Zeitüberschreitung wird das Skript beendet und, genau wie im obigen Fall des Verbindungsabbruchs, eine registrierte Shutdown-Funktion ausgeführt. Um zu überprüfen, ob es sich um einen Abbruch aufgrund von Zeitüberschreitung handelt, kann die Funktion connection_status() benutzt werden. Sie gibt 2 zurück, wenn es sich um eine Zeitüberschreitung handelt.

Zu bemerken ist, dass der ABORTED- und der TIMEOUT-Status gleichzeitig auftreten können. Dies ist möglich, wenn PHP angewiesen wird, Benutzerabbrüche zu ignorieren. PHP wird feststellen, dass der Benutzer die Verbindung abgebrochen hat, das Skript allerdings läuft weiter. Sollte es dann das Zeitlimit erreichen, wird es abgebrochen und eine Shutdown-Funktion, wenn definiert, wird aufgerufen. Zu diesem Zeitpunkt kann man feststellen, dass connection_timeout() und connection_aborted() TRUE zurückgeben. Diese beiden Statusmöglichkeiten können auch durch einen Aufruf der Funktion connection_status() abgefragt werden. Sie liefert ein Bitfeld des aktiven Status. Wenn beispielsweise TIMEOUT und ABORTED aktiv sind, wird 3 zurückgegeben.


12 BenutzerBeiträge:
- Beiträge aktualisieren...
a1n2ton at gmail dot com
12.12.2009 22: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.09.2009 8: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.02.2009 13: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 wont work if the output has started - but the a simple redirect wouldn't work anyway.

Thanks for the tip arr1
fanfear at yahoo dot com
5.01.2009 10: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
1.04.2008 23: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.11.2007 11: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.11.2006 20: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.09.2005 15: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.12.2004 20: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.09.2004 12: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.02.2004 14: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
7.08.2003 8: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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)