Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PHP script trick the browser into thinking the HTTP request is over?

I first configure my script to run even after the HTTP request is over

 ignore_user_abort(true);

then flush out some text.

 echo "Thats all folks!";
 flush();

Now how can I trick the browser into thinking the HTTP request is over? so I can continue doing my own work without the browser showing "page loading".

 header(??) // something like this?
like image 476
Robin Rodricks Avatar asked Sep 17 '09 03:09

Robin Rodricks


3 Answers

Here's how to do it. You tell the browser to read in the first N characters of output and then close the connection, while your script keeps running until it's done.

<?php
ob_end_clean();
header("Connection: close");
ignore_user_abort(true); // optional
ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Will not work
flush();            // Unless both are called !

// At this point, the browser has closed connection to the web server

// Do processing here
echo('Text user will never see');
?>
like image 69
2 revs, 2 users 97% Avatar answered Sep 24 '22 17:09

2 revs, 2 users 97%


Headers won't work (they're headers, so they come first)

I don't know of any way to close the http connection without terminating the script, though I suppose there's some obscure way of doing it.

Telling us what you want to do after the request is done would help us give better suggestions.

But generally, I'd be thinking about one of the following:

1) Execute some simple command-line script (using exec()) that looks like:

#!/bin/sh
php myscript.php <arg1> <arg2> .. <argN> &

Then kick that off from your http-bound script like:

<?PHP
exec('/path/to/my/script.sh');
?>

Or:

2) Write another program (possibly a continuously-running daemon, or just some script that is cronned ever so often), and figure out how your in-request code can pass it instructions. You could have a database table that queues work, or try to make it work with a flat file of some sort. You could also have your web-based script call some command-line command that causes your out-of-request script to queue some work.

At the end of the day, you don't want your script to keep executing after the http request. Assuming you're using mod_php, that means you'll be tying up an apache process until the script terminates.

like image 33
timdev Avatar answered Sep 22 '22 17:09

timdev


Maybe this particular comment on php.net manual page will help: http://www.php.net/manual/en/features.connection-handling.php#71172

like image 4
Lukman Avatar answered Sep 24 '22 17:09

Lukman