PHP Background Run

Source: Internet
Author: User
This digest is from CSDN education "grassroots" magazine, issue fourth

Recently in the consideration of the project for the user mass mail when thought of this method, feel also useful, so recorded (the project is: the user to the actual situation to his customers to send e-mail, his number of customers is thousands, according to the situation selected customers, write good mail point after sending to wait for all these messages are not too realistic, So consider running in the background, this method uses the HTTP features, first of all to tidy up the idea:
1.HTTP is stateless.
2.HTTP is request-response mode
3.HTTP is built on top of TCP (TCP based on IP, each request browser will use a random port with the server Web port (such as 80) to establish a socket connection, the browser's random port can be seen through $_server)
4. When requesting a Web resource (this article refers to a PHP file), the browser waits for a response from the Web server (Apache in this article) until the response ends
5. If the user clicks on the Stop button on the browser during the wait, the browser shuts down the TCP connection, that is, the request-reply process to abort the current HTTP, and according to the understanding of TCP, the abort should be to send a TCP instruction to the server side
6. The underlying connection TCP is off, and the current outstanding response is of course not output to the browser.
The above are all well understood, but the 4th has details:
The Web server responds with a header message in the HTTP header: Connection will tell you how the browser connection is maintained, typically:
Connection:keep-alive
And there's another head that says how long to keep: keep-alive:300.
What happens if the server responds by saying that the connection is closed (connection:close)? The browser stops waiting for a response (RFC 2616)
That now if the user requests the PHP output HTTP header: Connection:close. And the output of these headers to the browser, and then continue to execute the following code, what will be the effect?
The response to the browser is the page request is finished, but PHP is not finished, that is, will continue to execute, which implements the browser and the PHP request asynchronous execution of the effect
Example:
Ob_end_clean (); #清除之前的缓冲内容, this is required, if the previous cache is not empty, there may be HTTP headers or other content, resulting in the subsequent content can not be output in a timely manner
Header ("Connection:close"); #告诉浏览器, the connection is closed so the browser does not have to wait for the server to respond
#可以发送200状态码 to these requests is successful, otherwise the browser may retry, especially if there is an agent in the case
Ob_start (); #开发当前代码缓冲

{{Logical Code

echo "some processing";

Logical Code}}

The following output some header information for HTTP
$size =ob_get_length ();
Header ("Content-length: $size");
Ob_end_flush (); #输出当前缓冲
Flush (); #输出PHP缓冲

#休眠PHP, that is, the execution of the current PHP code is stopped, 1 seconds after PHP was awakened,
#PHP唤醒后, proceed to the following code, but this time the result of the above code has been output browser,
#也就是浏览器从HTTP头中知道了服务端关闭了连接, the browser will not be waiting for a response from the server,
#反应给客户的就是页面不会显示处于加载状态中, in other words, users can switch off the current page, or switch off the browser,
#PHP唤醒后继续执行下面的代码, this also implements the effect of PHP background execution,
#休眠的作用只是让php先把前面的输出作完, do not rush to execute the following code immediately, take a break, that is to say the following code
#执行的时候前面的输出应该到达浏览器了
Sleep (1);
Echo ' Here the output user does not see, the background runs ';

Any output from the following code will not be output to the browser, because the HTTP connection is closed.
So the execution of the following code belongs to the background run

Set_time_limit (0); #不受时间限制
$f = fopen (' 1.txt ', ' A + ');
for ($i =0; $i <1000; $i + +) {
if (fwrite ($f, $i. "

") = = = FALSE) {
echo "Cannot write to file ($filename)";
}
}
Fclose ($f);

Other: This is to let PHP actively tell the browser to end the conversation, the process should be very fast, PHP received the request immediately after the HTTP to the browser, but sometimes it is the case that PHP to do something first, and then the connection is broken off the HTTP response back to the browser, But if there is a network or some other unexpected situation caused the browser to shut down or lose the connection with the server, PHP response header output to the browser, PHP will continue to do?

Requests from the browser-answer this process is the Web server, if the request is PHP or other server-side language, according to the configuration of servers (LoadModule AddType These) requests for these resources will be transferred to the corresponding language processor, such as all. PHP access is performed by PHP parsing, and the results returned to Apache,apache are returned to the browser, but if these responses are not output to the browser, Apache notifies php,php to abort the execution of the current request file.
In other words, if the user shuts down the browser during a request, or the point stop button, the requested PHP code may be executed only half, not finished, if this time is doing some database write operations, the data may not be written completely. But also only has the output when PHP will receive the client has aborted the notice, if PHP does not have any output, even if the browser closes, the PHP code will be completely executed, then when will PHP output? Typically PHP has an output buffer, which is output when the buffer is full or when the program ends normally.
Why is there output when PHP know whether the browser is exited, presumably because the Apache output failed to feedback to PHP, if there is no output, PHP on the side silently execute, Apache does not notify it
In this case, if PHP continues to execute, you can use some of the connection control functions in PHP to ignore the client exit connection:
Ignore_user_abort, this function indicates whether or not to abort PHP execution after the client has been disconnected. Default is Abort
In other words, in the process of requesting the browser is not normal exit PHP can be known, may be through connection_status () to get the connection status:
0? Normal
1? Stop
2? PHP Execution timed out
These three states can be superimposed, that is, 3? Abort +php Execution Timeout
The problem is when we call Connection_status () to get the state of the connection, in the normal code call, get is 0, but if the browser is aborted, PHP execution is aborted, in general code this function can not be very good to see the expected results, PHP provides a hook:register_shutdown_function that the method is used to register a request at the end of the callback, whether the request is a normal end or an unexpected end, as long as PHP in the execution of this callback is bound to be called to. You can view the Connection_status () return value in this method,
function shutdown () {
$f = fopen (' 1.txt ', ' A + ');
Fwrite ($f, Connection_status ());
}

Register_shutdown_function (' Shutdown ');

while (1) {
#如果注掉, the user points to stop, PHP will also execute to timeout, file 1.txt is written to 2 PHP execution timeout
#如果不注掉, the user points the stop, the file 1.txt is written in 1-user abort
echo + + $i. "
";
}

PHP Background Run full code

/////
Ob_start ();
Set_time_limit (0);
Ignore_user_abort (TRUE);
Header ("content-type:text/html; Charset=utf-8 ");
Header ("Connection:close");
Ob_end_flush ();
Flush ();

Crawl Code

.....

?>

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.