5

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This gives me error 126. I think I need administrator privilege to run the command and also my script located at /home/administrator/scripts this path. I think web server is not give the permission to access outside of /var/www folder. is it right?
@SubhojitMukherjee Did you set the permissions on your script so that the webserver can run it? (e.g. "chmod o+rx sync.sh"). Does the script work when you run it from your user account?
Try sh sync.sh. That doesn't require sync.sh to be executable.
3

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.

3 Comments

The problem is that, my sync file located at /home/administrator/scripts so the command will access the outside www folder?
@SubhojitMukherjee It depends on how PHP is setup, but normally, it would be possible. Just give the absolute path to the script.
I know this is old but just had to do this so thought I'd comment here: be aware that if you are running the PHP script as part of a web application, the user will be the user that runs in the web server context, not the same as in the commandline context. So you might log in as a user and test the script and it works, but then as part of a web application it fails, because the web server does not run as the logged in user. To make that work: "sudo -u username /path" where username is the name of the script owner, and path is the full path to the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.