3

I have two files, file_a.php and file_b.php. In file file_a.php, I'm trying to execute file_b.php as a "background process". I tried two ways I have found here on stackoverflow, but i can't make it work:

file_a.php (exec solution)

echo "Start ".time()."<br>";
exec("php -f /Path/to/file/file_b.php /dev/null &");
echo "End ".time()."<br>";

file_a.php (curl solution)

echo "Start ".time()."<br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.1:8888/file/file_b.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_exec($ch);
curl_close($ch);
echo "End ".time()."<br>";

file_b.php (5 seconds delay and a sample mail send)

set_time_limit(5);//setting five seconds delay
for ($i = 0; $i < 4; ++$i) {

    sleep(1);
}

// the message
$msg = "line of text";
// send email
mail("testmail@test.io","My subject",$msg)

I'm trying to call file_a.php and execute file_b.php without waiting 5 seconds in file_a.php, exactly as a background process. There is a way to manage a similar behavior in PHP before PHP 7 for which i have seen some dedicated libraries?

Flinsch
  • 4,296
  • 1
  • 20
  • 29
user31929
  • 1,115
  • 20
  • 43
  • 1
    Why do you need to run this background process? Can it wait an hour or does it have to be done now? Seems like you need a cron job – Andreas Jan 30 '19 at 15:44
  • i want to free user who use file_a.php from waiting until the end of file_b.php execution (in real life application file_b.php will create an long execution time, something like 4 or 5 seconds, i need a very quick response for the file_a.php instead) – user31929 Jan 30 '19 at 16:57

1 Answers1

0

Create a file background.sh with the following content

#!/bin/bash

/usr/bin/php -f /Path/to/file/file_b.php &

and then call it using the first method

echo "Start ".time()."<br>";
exec("/bin/bash background.sh");
echo "End ".time()."<br>";

The shell will read the BASH script, run the PHP file in background and immediately return to your original script.

The more robust solution is to use some queue system, e.g. PHP-Resque

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26