Tratamento de Conexões
O estado de uma conexão é mantido internamente no PHP. Existem 4
estados possíveis:
- 0 - NORMAL
- 1 - ABORTADO
- 2 - EXPIRADO
- 3 - ABORTADO e EXPIRADO
Quando um script PHP está sendo executado normalmente, o estado NORMAL está ativo.
Se o cliente remoto desconecta, o estado ABORTADO é
ativado. Uma desconexão do cliente remoto é normalmente causada pelo
usuário pressionando o botão de parada. Se o tempo limite imposto pelo PHP (veja
set_time_limit()) é alcançado, o estado EXPIRADO
é ativado.
É possível decidir se a desconexão do cliente cause ou não uma
interrupção no script. As vezes é útil deixar o script em execução
até que seja concluído mesmo se não houver nenhum navegador remoto recebendo
a saída. O comportamento padrão, no entanto, é a interrupção
do script quando o cliente remoto se desconecta. Esse comportamento pode ser
configurado através da diretiva ignore_user_abort do php.ini, assim como pela
diretiva correspondente php_value ignore_user_abort
no
httpd.conf do Apache ou
com a função ignore_user_abort(). Se o PHP não for instruído
a ignorar o aborto por parte do usuário e ele abortar, o script
será encerrado. A única exceção é se uma função de finalização tiver sido
registrada usando register_shutdown_function(). Com uma
função de finalização, quando um usuário remoto clica no botão de parada, a
próxima vez que o script tentar gerar alguma saída, o PHP detectará que
a conexão foi cancelada e a função de finalização é chamada.
Essa função de finalização também será chamada no fim do script
mesmo que ele termine normalmente, então para fazer algo diferente caso o cliente
desconecte, a função connection_aborted() pode ser usada.
Essa função retorna true
se a conexão foi
abortada.
O script também pode ser finalizado pelo temporizador interno.
O tempo limite padrão é de 30 segundos. Pode ser alterado usando a
diretiva max_execution_time do php.ini ou a diretiva correspondente
no httpd.conf do Apache php_value max_execution_time
assim como com a função
set_time_limit(). Quando o temporizador
chega ao limite, o script será abortado e assim como o caso acima
de desconexão pelo cliente, se uma função de finalização foi registrada, ela será
chamada. Dentro da função de finalização, pode ser verificado se a
causa da finalização foi tempo limite excedido chamando-se a
função connection_status(). Essa função retornará
2 se a causa foi tempo limite excedido.
Importante notar que ambos os estados ABORTADO e EXPIRADO
podem estar ativos ao mesmo tempo. Isso é possível se o PHP
for instruído a ignorar o aborto causado pelo usuário. O PHP continuará a perceber que
o usuário pode ter quebrado a conexão, mas o script continuará
sendo executado. Se tempo limite for alcançado, ele será abortado e
sua função de finalização, se existente, será chamada. Nesse ponto,
a função connection_status()
retornará 3.
tom lgold2003 at gmail dot com ¶15 years ago
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); ob_start();
echo ('Text user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush(); flush(); ob_end_clean();
sleep(5);
echo('Text user will never see');
?>
arr1 at hotmail dot co dot uk ¶17 years ago
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(); ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush(); flush(); 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
Lee ¶20 years ago
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.
mheumann at comciencia dot cl ¶11 years ago
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();
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.
Marco ¶7 years ago
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';
a1n2ton at gmail dot com ¶14 years ago
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();
?>
Ilya Penyaev ¶12 years ago
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
ignore_user_abort(true);
header("Location: ".$redirectUrl, true);
header("Connection: close", true);
header("Content-Length: 0", true);
ob_end_flush();
flush();
fastcgi_finish_request(); sleep (5); ?>
Anonymous ¶12 years ago
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);
if(!ob_start("ob_gzhandler"))
ob_start();
echo $stringToOutput;
$size = ob_get_length();
header("Content-Length: $size");
header('Connection: close');
ob_end_flush();
ob_flush();
flush();
if (session_id()) session_write_close();
}
?>
Anonymous ¶16 years ago
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();
pulstar at mail dot com ¶21 years ago
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.
Jean Charles MAMMANA ¶16 years ago
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...