Run PHP Task Asynchronously

后端 未结 15 1238
青春惊慌失措
青春惊慌失措 2020-11-22 15:15

I work on a somewhat large web application, and the backend is mostly in PHP. There are several places in the code where I need to complete some task, but I don\'t want to m

15条回答
  •  耶瑟儿~
    2020-11-22 15:27

    Here is a simple class I coded for my web application. It allows for forking PHP scripts and other scripts. Works on UNIX and Windows.

    class BackgroundProcess {
        static function open($exec, $cwd = null) {
            if (!is_string($cwd)) {
                $cwd = @getcwd();
            }
    
            @chdir($cwd);
    
            if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
                $WshShell = new COM("WScript.Shell");
                $WshShell->CurrentDirectory = str_replace('/', '\\', $cwd);
                $WshShell->Run($exec, 0, false);
            } else {
                exec($exec . " > /dev/null 2>&1 &");
            }
        }
    
        static function fork($phpScript, $phpExec = null) {
            $cwd = dirname($phpScript);
    
            @putenv("PHP_FORCECLI=true");
    
            if (!is_string($phpExec) || !file_exists($phpExec)) {
                if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
                    $phpExec = str_replace('/', '\\', dirname(ini_get('extension_dir'))) . '\php.exe';
    
                    if (@file_exists($phpExec)) {
                        BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
                    }
                } else {
                    $phpExec = exec("which php-cli");
    
                    if ($phpExec[0] != '/') {
                        $phpExec = exec("which php");
                    }
    
                    if ($phpExec[0] == '/') {
                        BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
                    }
                }
            } else {
                if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
                    $phpExec = str_replace('/', '\\', $phpExec);
                }
    
                BackgroundProcess::open(escapeshellarg($phpExec) . " " . escapeshellarg($phpScript), $cwd);
            }
        }
    }
    

提交回复
热议问题