简体   繁体   中英

Get return value from a bash script with PHP

How to exectue a shell file with PHP?

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? 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?

Take a look at the exec() function. You can pass in a return_var which will hold the exit code from the shell script.

$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.

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.

According to the documentation :

Return Values

The output from the executed command or NULL if an error occurred.

Just get the return value of that function.

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

And $result will contain what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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