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?
The PHP functions to execute shell command are: shell_exec(), exec() or system(). These functions are remarkably similar but have slight differences.
Show activity on this post. Put that at the top of your script, make it executable ( chmod +x myscript. php ), and make a Cron job to execute that script (same way you'd execute a bash script). You can also use php myscript.
echo "<pre>$output</pre>" ; ?> The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.
PHP is primarily used on Server-side (and JavaScript on Client Side) to generate dynamic web pages over HTTP, however you will be surprised to know that you can execute a PHP in a Linux Terminal without the need of a web browser.
You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.
$old_path = getcwd(); chdir('/my/path/'); $output = shell_exec('./script.sh var1 var2'); chdir($old_path);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With