php中system()不返回輸出的解決方法:在命令中通過(guò)附加【2 >& 1】來(lái)將標(biāo)準(zhǔn)錯(cuò)誤重定向到標(biāo)準(zhǔn)輸出即可,例如【exec('some_command –option 2>& 1',$ output,$ ret);】。
本文操作環(huán)境:windows10系統(tǒng)、php 7、thinkpad t480電腦。
最近在工作時(shí)意外發(fā)現(xiàn)執(zhí)行像'ls'這樣的常用命令,exec()能夠工作正常,例如:
exec('ls',$輸出,$ retval); var_dump($ output,$ retval); // $ output包含文件名數(shù)組,retval === 0
但是當(dāng)我嘗試執(zhí)行另一個(gè)程序時(shí),我卻無(wú)法得到輸出,如下:
exec('some_command --a_parameter',$ output ,$ retval); var_dump($ output,$ retval); // $ output包含一個(gè)空數(shù)組,結(jié)束$ retval === 0
從命令行直接執(zhí)行命令時(shí)會(huì)打印一些行,我知道命令執(zhí)行成功了,我可以看到結(jié)果(一些文件更新,數(shù)據(jù)添加等),但是我卻看不到輸出。
exec()函數(shù)將只捕獲標(biāo)準(zhǔn)輸出。我并不能確定標(biāo)準(zhǔn)錯(cuò)誤總是發(fā)送到apache錯(cuò)誤日志,但似乎是可以的。
如果你不需要使用unix系統(tǒng),其實(shí)我們可以通過(guò)在命令中附加 2>& 1 來(lái)將標(biāo)準(zhǔn)錯(cuò)誤重定向到標(biāo)準(zhǔn)輸出,這樣問(wèn)題就可以得到解決了,例如:
exec('some_command --option 2>& 1',$ output,$ ret);
推薦學(xué)習(xí):php培訓(xùn)