[php] Run Bash Command from PHP

I have a bash script, that I run like this via the command line:

./script.sh var1 var2

I am trying to execute the above command, after I call a certain php file.

What I have right now is:

$output = shell_exec("./script.sh var1 var2");
echo "<pre>$output</pre>";

But it doesn´t work. I tried it using exec and system too, but the script never got executed.

However when I try to run shell_exec("ls"); it does work and $output is a list of all files.

I am not sure whether this is because of a limitation of the VPS I am using or if the problem is somewhere else?

This question is related to php bash exec

The answer is


Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh


Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to exec

I do not understand how execlp() works in Linux Running a Python script from PHP How do I execute a Shell built-in command with a C function? What are the uses of the exec command in shell scripts? php exec() is not executing the command How to call execl() in C with the proper arguments? Run Bash Command from PHP PHP shell_exec() vs exec() Ruby, Difference between exec, system and %x() or Backticks How to execute an external program from within Node.js?