php execute a background process

前端 未结 19 1438
萌比男神i
萌比男神i 2020-11-21 07:04

I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware

19条回答
  •  渐次进展
    2020-11-21 07:40

    Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.

    function LaunchBackgroundProcess($command){
      // Run command Asynchroniously (in a separate thread)
      if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){
        // Windows
        $command = 'start "" '. $command;
      } else {
        // Linux/UNIX
        $command = $command .' /dev/null &';
      }
      $handle = popen($command, 'r');
      if($handle!==false){
        pclose($handle);
        return true;
      } else {
        return false;
      }
    }
    

    Note 1: On windows, do not use /B parameter as suggested elsewhere. It forces process to run the same console window as start command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use /B.

    Note 2: The empty double quotes after start "" are required if the command is a quoted path. start command interprets the first quoted parameter as window title.

提交回复
热议问题