简体   繁体   English

使用PHP从bash脚本获取返回值

[英]Get return value from a bash script with PHP

How to exectue a shell file with PHP? 如何用PHP表示shell文件?

I have a file called sync.sh, so how to run the file in php and how to take the response after complete the execution? 我有一个名为sync.sh的文件,那么如何在php中运行该文件以及如何在完成执行后获取响应? I think shell_exec() will help to trigger the file but how can I get the response that script is completed the task properly or not? 我认为shell_exec()将有助于触发文件,但是如何才能获得脚本完成任务的响应?

Take a look at the exec() function. 看一下exec()函数。 You can pass in a return_var which will hold the exit code from the shell script. 您可以传入一个return_var,它将保存shell脚本中的退出代码。

$out = array();
$status = -1;

exec( '/path/to/sync.sh', $out, $status );

if ( $status != 0 ) {
    // shell script indicated an error return
}

One thing to watch out for is that the script will run with the web server's permissions, not your own as a user. 需要注意的一点是,脚本将使用Web服务器的权限运行,而不是作为用户自己运行。

Also, be sure to heed the doc's security-related warning: 另外,请务必注意文档与安全相关的警告:

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands. 当允许将用户提供的数据传递给此函数时,请使用escapeshellarg()或escapeshellcmd()以确保用户不会欺骗系统执行任意命令。

According to the documentation : 根据文件

Return Values 返回值

The output from the executed command or NULL if an error occurred. 执行命令的输出,如果发生错误,则为NULL。

Just get the return value of that function. 只需获取该函数的返回值。

$result = shell_exec('sync.sh');

And $result will contain what you want. $result将包含您想要的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM