Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Bash Command from PHP

Tags:

bash

php

exec

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?

like image 277
r0skar Avatar asked Jun 15 '12 14:06

r0skar


People also ask

Can PHP run shell command?

The PHP functions to execute shell command are: shell_exec(), exec() or system(). These functions are remarkably similar but have slight differences.

How do I run a PHP file in bash?

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.

How do I execute a PHP command?

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.

Can PHP run on Linux?

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.


1 Answers

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); 
like image 98
Robert K Avatar answered Sep 21 '22 16:09

Robert K