php execute shell command
shell_exec
(PHP 4, PHP 5, PHP 7, PHP 8)
shell_exec — Выполнить команду через оболочку и вернуть вывод в виде строки
Описание
Эта функция идентична оператору с обратным апострофом.
Список параметров
Команда, которая будет выполнена.
Возвращаемые значения
Ошибки
Примеры
Пример #1 Пример использования shell_exec()
Смотрите также
User Contributed Notes 33 notes
In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
To run a command in background, the output must be redirected to /dev/null. This is written in exec() manual page. There are cases where you need the output to be logged somewhere else though. Redirecting the output to a file like this didn’t work for me:
# this doesn’t work!
shell_exec ( «my_script.sh 2>&1 >> /tmp/mylog &» );
?>
Using the above command still hangs web browser request.
Seems like you have to add exactly «/dev/null» to the command line. For instance, this worked:
# works, but output is lost
shell_exec ( «my_script.sh 2>/dev/null >/dev/null &» );
?>
But I wanted the output, so I used this:
proc_open is probably a better solution for most use cases as of PHP 7.4. There is better control and platform independence. If you still want to use shell_exec(), I like to wrap it with a function that allows better control.
Something like below solves some problems with background process issues on apache/php. It also
A simple way to handle the problem of capturing stderr output when using shell-exec under windows is to call ob_start() before the command and ob_end_clean() afterwards, like this:
‘The system cannot find the path specified’.
I’m not sure what shell you are going to get with this function, but you can find out like this:
= ‘set’ ;
echo «» ;
?>
On my FreeBSD 6.1 box I get this:
USER=root
LD_LIBRARY_PATH=/usr/local/lib/apache2:
HOME=/root
PS1=’$ ‘
OPTIND=1
PS2=’> ‘
LOGNAME=root
PPID=88057
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
SHELL=/bin/sh
IFS=’
‘
Very interesting. Note that the PATH may not be as complete as you need. I wanted to run Ghostscript via ImageMagik’s «convert» and ended up having to add my path before running the command:
I had trouble with accented caracters and shell_exec.
Executing this command from shell :
Vidéos D 0 Tue Jun 12 14:41:21 2007
Desktop DH 0 Mon Jun 18 17:41:36 2007
Using php like that :
Vid Desktop DH 0 Mon Jun 18 17:41:36 2007
The two lines were concatenated from the place where the accent was.
I found the solution : php execute by default the command with LOCALE=C.
I just added the following lines before shell_exec and the problem was solved :
Just adapt it to your language locale.
Here is a easy way to grab STDERR and discard STDOUT:
add ‘2>&1 1> /dev/null’ to the end of your shell command
For example:
= shell_exec ( ‘ls file_not_exist 2>&1 1> /dev/null’ );
?>
Here is my gist to all:
On Windows, if shell_exec does NOT return the result you expected and the PC is on an enterprise network, set the Apache service (or wampapache) to run under your account instead of the ‘Local system account’. Your account must have admin privileges.
To change the account go to console services, right click on the Apache service, choose properties, and select the connection tab.
How to get the volume label of a drive on Windows
print GetVolumeLabel ( «c» );
?>
Note: The regular expression assumes a english version of Windows is in use. modify it accordingly for a different localized copy of Windows.
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage. Shell scripts that start with #!/usr/bin/bash return their output properly.
A solution is to force a clean environment. PHP CLI no longer had the CGI environment variables to choke on.
// Binary garbage.
$ExhibitA = shell_exec ( ‘/home/www/myscript’ );
?>
— start /home/www/myscript
#!/usr/local/bin/phpcli
echo( «Output.\n» );
Be careful as to how you elevate privileges to your php script. It’s a good idea to use caution and planing. It is easy to open up huge security holes. Here are a couple of helpful hints I’ve gathered from experimentation and Unix documentation.
Things to think about:
1. If you are running php as an Apache module in Unix then every system command you run is run as user apache. This just makes sense.. Unix won’t allow privileges to be elevated in this manner. If you need to run a system command with elevated privileges think through the problem carefully!
2. You are absolutely insane if you decide to run apache as root. You may as well kick yourself in the face. There is always a better way to do it.
3. If you decide to use a SUID it is best not to SUID a script. SUID is disabled for scripts on many flavors of Unix. SUID scripts open up security holes, so you don’t always want to go this route even if it is an option. Write a simple binary and elevate the privileges of the binary as a SUID. In my own opinion it is a horrible idea to pass a system command through a SUID— ie have the SUID accept the name of a command as a parameter. You may as well run Apache as root!
As others have noted, shell_exec and the backtick operator (`) both return NULL if the executed command doesn’t output anything.
This can be worked around by doing anything like the following:
it took me a heck of a lot of head banging to finally solve this problem so I thought that I would mention it here.
If you are using Eclipse and you try to do something like
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:
This works fine for me as a substitute for SSI or the virtual() func.
How to execute shell commands via PHP
This post discusses how to execute shell commands via PHP. The ability to execute shell commands is a powerful feature and should be used carefully. As such, not all hosting providers will allow you to execute shell commands.
The PHP functions to execute shell command is: shell_exec(), exec() or system(). These functions are remarkably similar but have slight differences. Let’s take a look.
shell_exec(): string
The shell_exec() function returns a string or NULL value. The returned string will contain the output of the command that you executed. The shell_exec() function will, however, return a NULL if an error has occurred. You can also expect a NULL value if the command produces no output.
Next, let’s look at how you can use the shell_exec() function to return a directory listing of a Linux machine:
The exec() function returns the last line of the executed command as a string. This command can, however, also return FALSE if an error has occurred.
Next, let’s look at how you can use the exec() function to return memory information of a Linux machine:
The system() function is similar to exec() function. It will however display output directly (without using echo() or print()).
Finally, let’s see how the system command is used using the exec() example from above:
Wrapping up
As you can see, it is easy to execute shell commands in PHP. Also, the shell_exec(), exec(), or system() function must not be disabled in the php.ini file.
You may also be interested in
Updated:
Source:
Anto’s editorial team loves the cloud as much as you! Each member of Anto’s editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.
Support Anto Online and buy us a coffee. Anything is possible with coffee and code.
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.
Run External System Binary or Application
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
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 shell_exec() Examples
Return Complete Output as String with system()
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.
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?
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.
late but… write the command with path for success:
exec(“/usr/bin/mkdir dir”,$output,$return_val);
PHP shell_exec выполнение консольной команды
Пытаюсь написать выполнение консольной команды после нажатия на кнопку. Вот что получилось
к сожалению это не работает. В чем причина, так и не могу понять
3 ответа 3
PHP, скорее всего, отрабатывает и возвращает результат выполнения команды. Но на этом всё заканчивается, хотя ffmpeg продолжает работать. Нужно зациклить чтение шелла, примерно так (Найдено на ENSO):
При успешном выполнении должны получить что-то вроде :
Нашел то что мне нужно.
я сделал это немного проще чем ваше решение, единственное что еще не подключил, это то, что выдает ffmpeg «2>&1»
Единственное что не сделано, 2>&1 это то что выдает FFMPEG
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.17.40238
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
shell_exec
shell_exec — Выполняет команду через шелл и возвращает полный вывод в виде строки
Описание
Эта функция идентична оператору обратный апостроф.
Список параметров
Команда, которая будет выполнена.
Возвращаемые значения
Примеры
Пример #1 Пример использования shell_exec()
Примечания
Эта функция недоступна в безопасном режиме.
Смотрите также
User Contributed Notes 68 notes
In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
A simple way to handle the problem of capturing stderr output when using shell-exec under windows is to call ob_start() before the command and ob_end_clean() afterwards, like this:
‘The system cannot find the path specified’.
When following Kenneth’s method for executing root scripts via the nanoweb server mentioned on this page you would most likely need to be able to run a text-mode browser like lynx and pass the php script to it (works great).
After struggling for a while (lynx kept asking me to download the file instead of executing it), I realised that I had to install php-cgi additionally and modify the nanoweb config file to use that php interpreter instead of /usr/bin/php. (On Debian this is the CLI version).
apt-get install php5-cgi
After editing /etc/nanoweb/nanoweb.conf and a quick restart of the web server, lynx and links will execute your PHP scripts properly.
Hope this helps somebody else out there 🙂
To run a command in background, the output must be redirected to /dev/null. This is written in exec() manual page. There are cases where you need the output to be logged somewhere else though. Redirecting the output to a file like this didn’t work for me:
# this doesn’t work!
shell_exec ( «my_script.sh 2>&1 >> /tmp/mylog &» );
?>
Using the above command still hangs web browser request.
Seems like you have to add exactly «/dev/null» to the command line. For instance, this worked:
# works, but output is lost
shell_exec ( «my_script.sh 2>/dev/null >/dev/null &» );
?>
But I wanted the output, so I used this:
I had trouble with accented caracters and shell_exec.
Executing this command from shell :
Vidéos D 0 Tue Jun 12 14:41:21 2007
Desktop DH 0 Mon Jun 18 17:41:36 2007
Using php like that :
Vid Desktop DH 0 Mon Jun 18 17:41:36 2007
The two lines were concatenated from the place where the accent was.
I found the solution : php execute by default the command with LOCALE=C.
I just added the following lines before shell_exec and the problem was solved :
Just adapt it to your language locale.
it took me a heck of a lot of head banging to finally solve this problem so I thought that I would mention it here.
If you are using Eclipse and you try to do something like
Be careful as to how you elevate privileges to your php script. It’s a good idea to use caution and planing. It is easy to open up huge security holes. Here are a couple of helpful hints I’ve gathered from experimentation and Unix documentation.
Things to think about:
1. If you are running php as an Apache module in Unix then every system command you run is run as user apache. This just makes sense.. Unix won’t allow privileges to be elevated in this manner. If you need to run a system command with elevated privileges think through the problem carefully!
2. You are absolutely insane if you decide to run apache as root. You may as well kick yourself in the face. There is always a better way to do it.
3. If you decide to use a SUID it is best not to SUID a script. SUID is disabled for scripts on many flavors of Unix. SUID scripts open up security holes, so you don’t always want to go this route even if it is an option. Write a simple binary and elevate the privileges of the binary as a SUID. In my own opinion it is a horrible idea to pass a system command through a SUID— ie have the SUID accept the name of a command as a parameter. You may as well run Apache as root!
Here is a easy way to grab STDERR and discard STDOUT:
add ‘2>&1 1> /dev/null’ to the end of your shell command
For example:
= shell_exec ( ‘ls file_not_exist 2>&1 1> /dev/null’ );
?>
As others have noted, shell_exec and the backtick operator (`) both return NULL if the executed command doesn’t output anything.
This can be worked around by doing anything like the following:
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage. Shell scripts that start with #!/usr/bin/bash return their output properly.
A solution is to force a clean environment. PHP CLI no longer had the CGI environment variables to choke on.
// Binary garbage.
$ExhibitA = shell_exec ( ‘/home/www/myscript’ );
?>
— start /home/www/myscript
#!/usr/local/bin/phpcli
echo( «Output.\n» );
This will make strict comparisons to » return false.
regarding the «ping» test that was mentioned by andy25it at hotmail dot it:
this might not work if the target server is behind a firewall which drops icmp packets. a better approach would be the use of fsockopen(), which doesn’t use icmp. in the notes section of the function list, Alexander Wegener wrote a nice implementation of an isOnline() function which works with both http and https.
It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing «memory_limit» solved the problem.
I’m not sure what shell you are going to get with this function, but you can find out like this:
= ‘set’ ;
echo «» ;
?>
On my FreeBSD 6.1 box I get this:
USER=root
LD_LIBRARY_PATH=/usr/local/lib/apache2:
HOME=/root
PS1=’$ ‘
OPTIND=1
PS2=’> ‘
LOGNAME=root
PPID=88057
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
SHELL=/bin/sh
IFS=’
‘
Very interesting. Note that the PATH may not be as complete as you need. I wanted to run Ghostscript via ImageMagik’s «convert» and ended up having to add my path before running the command:
On Windows, if shell_exec does NOT return the result you expected and the PC is on an enterprise network, set the Apache service (or wampapache) to run under your account instead of the ‘Local system account’. Your account must have admin privileges.
To change the account go to console services, right click on the Apache service, choose properties, and select the connection tab.
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:
Easy way to capture error output in windows
Hope this helps someone
Also after lots of hair pulling why shell_exec didn’t want to work for me I found out that in my case some things needed to be set (which normally are set by default).
The strange thing was that I didn’t have to put these options when I would give the command on the command-line, only when I would call it with shell_exec.
So the complete command in php would be for me:
And putting en echo in front will help you a lot.
it should tell you something like this: