Brandon0
Brandon0

Reputation: 266

PHP Background Process Still Affecting Page Load

So I have found a number of tutorials/guides for running a php script as a background process, but no matter which code I use, the process still appears visible in the browser.

What I am doing is triggering a script that may take 5-10 seconds to run (relies on a third party API). I put the trigger at the very bottom of the page so that the page appears to render completely, but I have noticed that the browser status bar still shows the page as loading until the script runs. Additionally, Firebug is showing one (random?) image as loading until the php script is completely finished running. I can view the script in top and it is running as a separate process. How can I get the browser to stop waiting for it to finish though?

The code I'm using currently is:

shell_exec('sleep 30 >/dev/null 2>/dev/null &');

I've also tried using exec() but there wasn't any difference.

Disclaimer: My final code will use /usr/bin/GET, sleep is just to be obvious about what's going on.

Upvotes: 2

Views: 2166

Answers (5)

anonymous
anonymous

Reputation: 1

This is not currently possible.

Upvotes: -1

user69173
user69173

Reputation:

Here's a pretty minimal solution, based on http://php.net/features.connection-handling#71172 :

<?php
ob_end_clean();
ob_start();
?>
<!doctype html>
<html>
<head>
<title>sleep test</title>
</head>
<body>
<h1>sleep test</h1>
<p>going to sleep</p>
</body>
</html>
<?php
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
$start = date(DATE_RSS);
sleep(10);
file_put_contents('sleep-test.txt', $start."\n".date(DATE_RSS));
?>

Upvotes: 3

Brent Baisley
Brent Baisley

Reputation: 12721

Trying adding nohup in front of the command. You need PHP to disconnect from the process and continue on. Normally, if a parent process ends, the child process is killed. nohup will prevent this, and also prevent php from waiting for the child process to finish.

shell_exec('nohup sleep 30 >/dev/null 2>&1 &');

Upvotes: 1

Evert
Evert

Reputation: 99687

If it's a seemingly random image that doesn't stop loading, you might simply have a different issue altogether.

At the very least I would check which process is taking too long, and take it from there.

Upvotes: 0

jokz
jokz

Reputation: 13

ob_end_flush();

ignore_user_abort(1);

this two functions will help you if i rightly understand your problem.

Upvotes: -1

Related Questions