在使用一個php爬蟲的時候提示一定要用cli環境
我查看了當前php版本資訊如下:
我列印 PHP_SAPI 顯示 fpm-fcgi
如何才能變成 cli
伺服器環境是linux+nginx
補充:我能不能理解為cli一定是要命令列模式?
剛剛在命令列裡測試了PHP_SAPI 輸出了cli
問:能不能http類比調用實現cli
回複內容:
在使用一個php爬蟲的時候提示一定要用cli環境
我查看了當前php版本資訊如下:
我列印 PHP_SAPI 顯示 fpm-fcgi
如何才能變成 cli
伺服器環境是linux+nginx
補充:我能不能理解為cli一定是要命令列模式?
剛剛在命令列裡測試了PHP_SAPI 輸出了cli
問:能不能http類比調用實現cli
CLI = command-line interface = 命令列介面
你可以在php-fpm裡用popen或proc_open非同步呼叫php-cli執行一個php指令碼,比如:
例子1(popen): array('pipe','r'), //stdin (用fwrite寫入資料給管道) 1 => array('pipe','w'), //stdout(用stream_get_contents擷取管道輸出) 2 => array('pipe','w'), //stderr(用stream_get_contents擷取管道輸出) //2 => array('file','/tmp/err.txt','a') //stderr(寫入到檔案) ), $pipes, //管道(stdin/stdout/stderr) '/tmp', //當前PHP進程的工作目錄 array('foo' => 'bar') //php.ini 配置 variables_order = "EGPCS" 其中E表示$_ENV,否則$_ENV輸出為空白 ); //var_dump($pipes); //resource of type (stream) if(is_resource($proc)) { //stdin $stdin = serialize(array('time' => time())); fwrite($pipes[0], $stdin); //把參數傳給指令碼task.php fclose($pipes[0]); //fclose關閉管道後proc_close才能退出子進程,否則會發生死結 register_shutdown_function(function() use($pipes, $proc) { //事件驅動(指令碼結束事件),非同步回調 //stdout $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]); //stderr $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); //exit code (返回進程的終止狀態代碼,如果發生錯則返回-1) $status = proc_close($proc); $data = array( 'stdout' => $stdout, 'stderr' => $stderr, 'status' => $status, ); var_export($data); //echo json_encode($data); }); }}foo();//輸出:array ( 'stdout' => 'a:1:{s:4:"time";s:19:"2016-09-11 21:26:29";}', 'stderr' => '', 'status' => 0,)
cli就是命令列,linux下就是php這個命令。php執行命令列有很多方式,可以用exec等函數同步執行,也有方法非同步執行,去詳細地看看文檔吧
用終端直接運行指令碼就行