- How To Execute Shell Commands with PHP Exec and Examples?
- exec() Function Syntax
- Run External System Binary or Application
- Print Output
- Assign Return Value into Variable
- Return Complete Output as String with shell_exec()
- PHP shell_exec() Examples
- Return Complete Output as String with system()
- exec() Function vs shell_exec() Function
- 3 thoughts on “How To Execute Shell Commands with PHP Exec and Examples?”
- How to Execute Shell Commands in PHP
- PHP exec() Function Syntax
- Make a Directory Using exec()
- Using a Variable inside exec()
- Printing the Output from exec()
- Multi-line Output from exec()
- Set a Return Variable
- Return Output as a String with the PHP shell_exec() Function
- PHP system() Function
- Conclusion
- How to execute a shell script in PHP?
- Update 5/4/2011:
- 4 Answers 4
How To Execute Shell Commands with PHP Exec and Examples?
Php provides web-based functionalities to develop web applications. But it also provides system related scripting and execution features. The exec() function is used to execute an external binary or program from a PHP script or application. In this tutorial, we will look at different use cases and examples of exec() function like return value, stderr, shell_exec, etc.
exec() Function Syntax
The PHP exec() syntax is like below where single parameter is mandatory and other parameters are optional.
exec(string COMMAND, array OUTPUT, int RETURN_VARIABLE);
- COMMAND is the command we want to execute with the exec() function. The command should be a string value or variable. COMMAND is a mandatory parameter.
- OUTPUT is the output of the COMMAND execution. OUTPUT is an array that can hold multiple values or lines. OUTPUT is optional where it can be omitted.
- RETURN_VARIABLE is the return value of the given COMMAND. RETURN _VALUE is generally the process status of the command. RETURN_VALUE is an integer and optional to use.
Run External System Binary or Application
We will start with a simple example. We will provide the command we want to run on the local operating system. In this example, we will create a directory named data . This directory will be created in the current working path. We can also specify the path explicitly like /var/data .
We can list the created directory with Linux file command like below. We will also provide the directory name because exec() function will only show the last line of the output. We will use echo to print the command output.
Print Output
We have already looked at printing output but I want to explain more about printing output. exec() function output or return can be printed with echo but the printed part will be only last line. So in a multi-line output, we can not see the output with echo . If we want to see the whole output we should use the system() function which will be explained below.
But we can use the output parameter like below. In this example, we will put command output to the o . The output parameter is in array type so we will use print_r to print output.
From the output we can see that the executed ls command output is stored in the variable named $o as an array. Every item is a files or folder which is located under the current working directory.
Assign Return Value into Variable
Using echo is not a reliable way to get the return value. We can use variables to set return values and use whatever we want. In this example, we will set the process return value to the variable named v.
Return Complete Output as String with shell_exec()
PHP language provides different functions as an alternative to exec() . We can use the shell_exec() function which will create a shell process and run given command. In this example, we will look at ls command and print output. With the shell_exec() function we can not get the return value of the shell process or command.
PHP shell_exec() Examples
In this part, we will make more examples about the PHP shell_exec() function. We will run the different system and Linux commands like date , whoami , ifconfig and mkdir .
echo shell_exec('date'); echo shell_exec('whoami'); echo shell_exec('ifconfig');
Return Complete Output as String with system()
Another similar function is system() . system() function displays output directly without using echo or print . In this example, we will run the ls command again.
exec() Function vs shell_exec() Function
PHP also provides the shell_exec() function which is very similar to the exec() function. The main difference is shell_exec() function accepts a single parameter which is a command and returns the output as a string.
//Execude command in the shell with PHP exec() function //put the output to the $output variable exec("uname -a",$output,$return_val); print_r($output); //Execude command in the shell with PHP shell_exec() function //put the output into $out variable $out = shell_exec("uname -a"); echo $out;
3 thoughts on “How To Execute Shell Commands with PHP Exec and Examples?”
Commands like ls work fine but creating a directory in not working for me not sure if I need to change any permissions or anything.
Any idea? Reply
Almost certainly some kind of permissions problem. The user running the PHP script needs to have the ability to do what the command wants to do. Try creating a directory in /tmp and see if that works. Make sure your command is /bin/sh compatible since that’s hardcoded into PHP. Reply
late but… write the command with path for success:
exec(“/usr/bin/mkdir dir”,$output,$return_val); Reply
How to Execute Shell Commands in PHP
There are times when you need to run a shell command from inside a PHP program. This can be for several reasons such as running terminal-based programs or running common terminal commands like ls . PHP can execute any shell command and return its output as a string or array if needed.
In this tutorial, we will learn how to execute shell commands in PHP with examples.
PHP exec() Function Syntax
exec(command, output, return_variable)
Here is what each parameter is used for in exec()
- command — the only required argument in exec() . It is the terminal command to run
- output — do something with the output of the command. Can be used to return the output back into the PHP program as a string
- return_variable — put the output in the variable defined in this parameter
Make a Directory Using exec()
In this example, we will create a directory. We will do this using the Linux mkdir command and passing in the name of the directory we want to create.
The above command will create a directory in the same directory as the PHP file that executed it.
To create a directory in a different location on the system pass in a path before the name of the directory. This can be an absolute path (relative to root) or a relative path to the location of your program.
exec('mkdir /var/www/sites/skillsugar/public/test');
Using a Variable inside exec()
It is possible to pass variables into exec() by closing the ‘ (single quote) or » (double quote) and concatenating the variable in using a . (dot).
$file_name = 'new_dir'; exec('mkdir /home/vagrant/sites/skillsugar/public/' . $file_name);
$dir_name = 'new_dir'; exec('mkdir ' . $dir_name . '/file.txt');
Printing the Output from exec()
You can simply echo the output.
Multi-line Output from exec()
You will notice that the above example only prints the last line from the ls command. To get all the lines we can set an output variable in the second parameter of exec() and then print the array containing all the lines.
Array ( [1] => build [2] => cgi-bin [3] => css [4] => error_log [5] => example.txt #. [16] => test [17] => test.php [18] => test2 [20] => translations [21] => web.config )
Set a Return Variable
To get what the terminal command returned we can set a variable in the third parameter of exec() .
Return Output as a String with the PHP shell_exec() Function
To return a complete string from a shell execute command in PHP use the shell_exec() function instead. It works in the same way to exec() except it takes no arguments and will return the complete output as a string.
build cgi-bin css error_log example.txt #. test test.php test2 translations web.config
PHP system() Function
The system() PHP function works just like shell_exec() except you don’t need to print or echo the output string as it does this for you.
build cgi-bin css error_log example.txt #. test test.php test2 translations web.config
Conclusion
You now know how to execute a shell command in three different ways using PHP. exec() give you the most flexibility, but you will have to pass a second argument to get the complete output as a string. system() is the most basic way to execute a command and get the complete output but has limited functionality.
How to execute a shell script in PHP?
I have a script in /var/www/myscript.sh which creates folders and runs the command svn update for my projects. I need to execute this script by calling it in a PHP file in the browser (i.e. Localhost/test.php). I tried using functions shell_exec() and exec() but those did not work. I ran my shell script in terminal with su www-data && ./myscript.sh and it worked. What else am I missing?
Update 5/4/2011:
I added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers and it works, but this is very insecure. Is there another way to do this?
Possible dupe of stackoverflow.com/questions/5311384/… which was solved as a permission problem. Is yours a path problem (since you’ve successfully executed it as the apache user)?
4 Answers 4
- You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
- exec and shell_exec are disabled in php.ini
- The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . ‘/myscript.sh’);
You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:
And remove the exec, shell_exec entries if there are there.
It might also be wise for OP to check rwx permissions in the directory they’re attempting to execute from.
If it was disabled PHP would throw a very specific error explaining it which should be easily fixable, don’t know if it would be this!
I have added the disable_functions = exec to php.ini still not working and myscript.sh also has 777 permision
Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.
I would imagine you don’t want your shell script to be in your web root, as it would be visible to anyone with web access to your server.
I would recommend moving the shell script to outside of the webroot
i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works
You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don’t need to do this at all anyway.
Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it’ll be fine.
sudo su apache (or www-data) cd /var/www sh ./myscript
Also. what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won’t happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins — create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file