PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

영구적인 데이터베이스 접속> <원격 파일 사용하기
Last updated: Sun, 25 Nov 2007

view this page in

연결 제어

Note: 이 기능은 PHP version 3.0.7 이후부터 적용된 것들이다.

내부적으로 PHP는 연결의 상태를 다음 3가지중 하나로 설정한다. :

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT

PHP 스크립트가 일반적으로 실행되고 있을 때는 NORMAL 상태가 active된다. 만약 원격 클라이언트가 연결을 끊게되면 ABORTED 상태 flag가 켜지게 된다. 보통 클라이언트가 연결을 끊는 것은 사용자가 STOP 버튼을 눌렀을 때 일어난다. 만약 PHP가 설정한 시간 제한에 (set_time_limit()을 보라) 걸리게 되면 TIMEOUT 상태 flag가 켜지게 된다.

클라이언트가 연결을 끊었을 때 스크립트가 수행을 중단할 것인가 아닌가를 결정하여야 한다. 때때로 원격 브라우저가 어떤 결과도 받아들이지 않더라도 스크립트를 끝까지 실행하는 것이 편리할 때가 많다. 기본 동작은 클라이언트가 연결을 끊으면 스크립트도 중단되는 것이다. 이 동작은 ignore_user_abort라는 php3.ini 지시자(directive)나, php3_ignore_user_abort라는 Apache의 .conf의 지시자로 설정이 가능하고, ignore_user_abort() 함수를 사용하여 설정할 수도 있다. 만약 PHP에게 사용자가 내린 중지 명령을 무시하라고 말해주지 않았다면, 사용자의 중지 신호는 여러분의 스크립트를 종료시킨다. 단, register_shutdown_function()을 사용하여 shutdown 함수를 등록해 놓은 경우는 예외가 된다. shutdown 함수를 사용하면, 사용자가 STOP버튼을 눌렀을 때, 여러분의 스크립트는 남은 출력을 하려고 하고, PHP는 연결이 중단되었음을 인지하여 shutdown 함수를 호출하게 된다. shutdown 함수는 여러분의 스크립트가 정상적으로 종료되었을 때도 호출 된다. 만약 여기서 클라이언트의 연결 중단시에 다른 동작을 원한다면 connection_aborted() 함수를 사용하면 된다. 이 함수는 연결이 중단되었다면 TRUE를 반환한다.

스크립트는 내장된 스크립트 타이머에 의해 종료될 수 있다. 기본 timeout 시간은 30초로 되어 있다. 이 시간을 max_execution_time이라는 php3.ini 지시자(directive)나, 동일한 내용의 php3_max_execution_time이라는 Apache의 .conf 지시자에 의해 다르게 설정이 가능하고 set_time_limit() 함수를 사용하여 설정할 수도 있다. 설정한 시간이 경과하면 스크립트는 자동으로 중단되고, 이 스크립트는 위에 설명한 클라이언트와의 연결이 종료된 것처럼 동작한다. 따라서 shutdown 함수가 등록되어 있다면 이 함수가 실행된다. shutdown 함수내에서 이 함수가 timeout에 의해 호출된 것인가를 판단하려면 connection_timeout() 함수를 사용하면 된다. 이 함수는 timeout에 의해 shutdown 함수가 호출되었다면 TRUE를 반환한다.

한가지 유의할 사항은 ABORTED와 TIMEOUT 상태는 두 개가 동시에 active될 수 있다는 것이다. 이것은 PHP가 사용자 중단을 무시하도록 설정해 놓았을 때 생길 수 있다. 사용자가 연결을 끊었지만, 스크립트는 계속 실행되고, 시간 제한에 걸려 스크립트의 수행이 중단되고 shutdown 함수가 호출되면, connection_timeout()connection_aborted()함수 모두 TRUE를 반환하게 된다. connection_status()함수를 사용하여 두가지 상태 모두를 검사할 수 있다. 이 함수는 각 상태에 대한 active 정보를 bit 단위로 반환한다. 예를들어 위와같이 ABORT와 TIMEOUT 두 개의 상태가 모두 active되어 있다면 이 함수는 3을 반환한다.



add a note add a note User Contributed Notes
연결 제어
Jean Charles MAMMANA
01-Apr-2008 02: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 02: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 11: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 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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites