简体   繁体   English

关闭浏览器会阻止PHP脚本完成执行吗?

[英]Will closing the browser prevent a PHP script from finishing execution?

If an ajax request is made to server to run a script in backend and user closed the browser. 如果向服务器发出ajax请求以在后端运行脚本并且用户关闭了浏览器。 Will that script complete execution on backend if it started and was in midprocess? 如果脚本启动并处于中间进程,那么该脚本是否会在后端完成执行?

NO.. , PHP script will not terminate its execution. NO .. ,PHP脚本不会终止其执行。

YES.. it'll complete its execution. 是的..它将完成它的执行。

Once php script is initiated, it'll complete its execution and then will stop. 启动php脚本后,它将完成执行,然后停止。

because, php runs at server side, it can't be interrupted by client side simple event like browser window close . 因为,php在服务器端运行,它不能被客户端简单事件中断,如browser window close

But however client will not be able to see the output. 但是客户端无法看到输出。

for ex: 对于前:

Try This Code: 试试此代码:

//File Name: xyz.php
<?php
$fp=fopen("output.txt","w");
$count=0;
for($count=0;1;$count++){
//Infinite loop
fwrite($fp,"".PHP_EOL."".$count."");
}
fclose($fp);
?>

and now test this file, Even after you close the browser window, it'll continue to print inside that output file ( output.txt ). 现在测试这个文件,即使在关闭浏览器窗口后,它仍将继续在该输出文件( output.txt )中打印。

Don't forget to close that php script from command prompt or task manager though, or it'll fill up your HDD (I ran that for merely 10 secs, in which for 5 secs browser was closed and it consumed 160 MB!). 不要忘记从command prompttask manager关闭该php脚本,否则它将填满你的硬盘(我只运行了10秒,其中5秒浏览器已关闭,消耗160 MB!)。

Here is result analysis : 这是结果分析:

Initially File size was : 0Kb, 最初文件大小为:0Kb,

After five secs: 76 MB (Browser was on till this point). 五秒后:76 MB(浏览器开启至此时)。

After seven secs: 125 Mb (Assuming delay in browser close, Now browser is totally off), 七秒后:125 Mb(假设浏览器关闭延迟,现在浏览器完全关闭),

Still after 10 secs: 160 Mb ( It is proof that php is running in background :-)) 仍然在10秒后:160 Mb( 证明php在后台运行 :-))

Now I've switched off httpd and size is now constant. 现在我关闭了httpd ,现在大小不变。

If you want to see how that happens just add usleep before fwrite() 如果你想看看如何发生这种情况,只需在fwrite()之前添加usleep

as: 如:

usleep(1*1000*1000); // Sleep for 1 sec.
fwrite($fp,"".PHP_EOL."".$count."");

Now you can see it happening inside that output.txt file. 现在你可以在output.txt文件中看到它发生了。 even after you close the browser. 即使你关闭浏览器后。 however the result analysis given above will not be applicable here now(if only size of file factor is considered), because of delay factor. 但是由于延迟因素,上面给出的结果分析现在不适用(如果仅考虑文件因子的大小)。

Well, PHP is server side, it computes all the code and then sends the results to the client. 好吧,PHP是服务器端,它计算所有代码,然后将结果发送到客户端。 So I guess it finishes the script execution even if you close the browser. 因此,即使您关闭浏览器,我猜它也会完成脚本执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM