简体   繁体   中英

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. Will that script complete execution on backend if it started and was in midprocess?

NO.. , PHP script will not terminate its execution.

YES.. it'll complete its execution.

Once php script is initiated, it'll complete its execution and then will stop.

because, php runs at server side, it can't be interrupted by client side simple event like 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 ).

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!).

Here is result analysis :

Initially File size was : 0Kb,

After five secs: 76 MB (Browser was on till this point).

After seven secs: 125 Mb (Assuming delay in browser close, Now browser is totally off),

Still after 10 secs: 160 Mb ( It is proof that php is running in background :-))

Now I've switched off httpd and size is now constant.

If you want to see how that happens just add usleep before fwrite()

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. 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. So I guess it finishes the script execution even if you close the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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