Search code examples
phpbackground-process

Populating $_SERVER when using popen to run a php script in background


I'm using the following code to run the php script email/send-emails.php in the background:

if(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
   $phpExec = str_replace('/', '\\', dirname(ini_get('extension_dir'))).'\php.exe';
   if(!file_exists($phpExec))
      throw new Exception('Could not find executable: '.$phpExec);
} else {
   $phpExec = exec("which php-cli");
   if($phpExec{0} !== '/')
      $phpExec = exec("which php");
   if($phpExec{0} !== '/')
      throw new Exception('Could not find executable: '.$phpExec);
}

$exec = $phpExec.' email/send-emails.php';
$cmd = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? 'start /B '.$exec : $exec.' &';
pclose(popen($cmd, 'r'));

This works beautifully on both Windows and Linux. The only problem is that $_SERVER is populated with completely different values in the calling script and in the email script. For instance, the keys SERVER_PROTOCOL, SERVER_NAME, and REQUEST_URI are missing in the email script. I guess this makes sense, since the calling script is served through Apache, while the the email-script is not(?).

Is there a way to populate the missing values of $_SERVER when calling a php script using popen?


Solution

  • The easiest way would be to make a HTTP request for the file rather than using popen to run it.

    Otherwise in your send-emails.php script you could detect if the $_SERVER values were missing and populate them with some sensible defaults.