R
R
romasovest2018-04-12 07:59:02
PHP
romasovest, 2018-04-12 07:59:02

How to run background php?

It is necessary that when the user goes to index.php, the bg.php script is executed in the background, for example:

<?php	
sleep(10);
file_put_contents('test.txt', 'success');
?>

The result of executing bg.php is not important. But it is important that bg.php is executed after base.php is loaded (for this I added sleep to bg.php)
Now the task is solved like this - ajax to bg.php is performed in base.php, but would it be better with php?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2018-04-12
@frost18

1) Your version on Ajax, the problem is that the session will be blocked, and you will not go to other pages until the script completes execution, here you can call session_write_close(); but still it is a crutch option, but a working one.
2) If you have Apache, then you can do this:

echo 'ok';

set_time_limit(0);
ignore_user_abort(true);
header("Connection: close");
ob_flush();
flush();

sleep(10);
file_put_contents('test.txt', 'success');

But on hosting it didn’t work for me, because there is apache + nginx, and it doesn’t skip the Connection header, puts its own "keep-alive"
3) The option that suited me. When placing an order, I needed to do heavy operations (sending mail, sending to CRM, logs, etc.), but the result of these operations is not important.
public function isWin(){
  return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
public function backgroundProcess($command){
  if(!$this->isWin()){
    $command = $command.' > /dev/null &';
  }
  $result = exec($command);
  return $result;
}

Works on linux, the point is that "&" is added to the end of the command, which starts a new process.
$obj->backgroundProcess('php /path../bg.php');
PS In general, these are all exceptional situations, PHP should not work in asynchronous mode. Maybe it's better for you to make records in the database every time you visit the page. And then set up a CRON task scheduler that will execute your script on these records.

A
Antonio Solo, 2018-04-12
@solotony

php.net/manual/en/function.pcntl-fork.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question