Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return value from a bash script with PHP

Tags:

shell

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?

like image 941
Subhojit Mukherjee Avatar asked Dec 30 '11 07:12

Subhojit Mukherjee


1 Answers

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.

like image 96
nsanders Avatar answered Oct 10 '22 00:10

nsanders