php shell exec пример
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:
Функции запуска программ
Примечания
Открытые файлы с блокировкой (особенно открытые сессии) должны быть закрыты до выполнения программы в фоне.
Смотрите также
Эти функции также тесно связаны с оператором обратные кавычки («).
Содержание
User Contributed Notes 46 notes
exec(«php script.php parameters 2>dev/null >&- /dev/null &»);
Where.
— php is the path to your php script executer (php has to be specifically complied to be to do this)
— script.php is the script
— parameters are none or more parameters
— 2>dev/null redirects the stderr to a file
— &- switches off the stdout
— >dev/null redirects all other output to the file dev/null
— & direct script to run in background
What I found odd is that the script I was execing would run fine in the bg when executed from the command line, but not from the browser until I closed the stdin and stdout.
at LAST! tenacity pays off, days trying every little thing!
I didn’t want batch files. I’m trying to use PHP to get rid of batch files.
I didn’t want to call a file to parse the parameters to call a shell to call a file. I’ve got «systems» right now with batches tiered three and five deep.
I just wanted to run stuff.
CALL, tested on WinXP, will be testing on more OSes right away, in PHP4 and 5, with exec, system, works with popen, and passthru.
here is my lame sample function.
// all of the below are working in Win XP Pro
passthru ($shellcommand);
exec ($shellcommand);
system ($shellcommand);
shell_exec ($shellcommand);
$proc= popen ($shellcommand, «r»); //$proc contains output
LONG PATH NAMES WITH SPACES IN THEM ON WINDOWS!
all in a big long concatenated command line with multiple quoted-filename parameters
shell scripting bliss!
The only syntax I found to work for the command portion of an an exec() call on a Win2K devel platform is:
$cmd = «\»path-to-exe\» args file-name»;
where ‘path-to-exe’ has escaped double quotes, args are in the standard format, and ‘file-name’ has any backslashes escaped.
Note that the backslashes are escaped in the uploaded_file name, but not in the path to call the Winzip executable. Go figure!
To clarify even more about what has been said in the last few posts:
«exec», «backticks», «system» and so on will fail on Windows 2003 by default.
You must modify the security on cmd.exe to give the user account IUSR-computername the necessary permissions which are at least read & execute.
The note is about usage of exec() under windows.
Here is where i’m at right now (also TRYING to use exec() and passthru() on windows XP sp2):
$cmd = ‘»C:\my path with spaces\targetapp.exe» C:\mypathnospaces\targetfile.xxx’;
exec($cmd);
The above works.
________
Or, you can put your script into your directory C:\my path with spaces\, and work with php directly from there:
$cmd = ‘targetapp.exe «C:\my other path with spaces\targetfile.xxx»‘;
exec($cmd);
The above also works, provided of course your script has the correct working directory.
________
But. In your cmd.exe, you can issue:
«C:\my path with spaces\targetapp.exe» «C:\my other path with spaces\targetfile.xxx»
Although the above works perfectly in the cmd, the following php script does NOT work on my system:
$cmd = ‘»C:\my path with spaces\targetapp.exe» «C:\my other path with spaces\targetfile.xxx»‘;
exec($cmd,&$content);
As far as my few tryings go, the root of the problem lies in the fact that the command to execute has two passages enclosed inside double quotes. Another command which I’ve had working in the cmd but NOT with php is:
Maybe someone has a solution; I don’t (other than using chdir).
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use cacls command-line utility to do this.
cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F
gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
To fork a process I use the following code
( STDOUT ); //Close all output or it WON’T work
fclose ( STDIN );
fclose ( STDERR );
if( pcntl_fork ()) <
exit; //Return to the caller
>
//Code to run in the background
AFICT, the standard Unix Apache configuration causes an rare problem when running a job in the background. The MaxRequestsPerChild directive causes the child to terminate after 1000 requests, any background processes associated with the child will die with the child unless they are started with the «nohup» command. Thus, the proper way to start a job in the background is to use:
exec(‘nohup my-command > /dev/null 2>&1 &’)
Just a simple note to help people get rid of some headaches.
Make sure you use «\ » ( \ space) for the Linux\unix path and just » » space for fopen. These are both very basic things that you wouldn’t normally think to cause a problem, but when you try to pass slashes to fopen it either breaks or even better works incorrectly =D. And vise versa for any programs that use «\ » for spaces in file paths/names.
*Note this is alot of sudo code, and there are faster more effecient ways of doing the same operations, but I thought this might help those who were going crazy over filepaths =D.
Well, I had this issue when I wanted to start an indefinitely running PERL script from PHP. Somehow I could not make the PHP script to return after executing the PERL script. So finally I came to following solution:
PHP file
——————-
( «perl /home/chatserver.pl > /dev/null» );
?>
——————-
This script will be run over HTTP.
Hopefully it helps someone 🙂
Margus
If you plan to start programs on the server that show message boxes (things that require OK from the server-side), or remain (like notepad.exe), and the exec-command seems to go into an deadly loop, then MAYBE your program has started, but you can’t see it. Because the web server runs as an system process, and it isn’t allowed to interact with the desktop.
To solve a part of the problem (to see the programs you execute), in the control panel in Windows, goto Administration->Services, right-click the server-service, goto Properties and on the second tab (login?) and check the box about allowing the service to interact with the desktop. Click OK. Restart the webserver, and MAKE SURE it is restarted for real (i.e. look in the task manager so the service goes _down_), otherwise the desktop-option won’t take.
Next phase would be to stop PHP from waiting for the processes to complete (this is what makes PHP «loop»). I solved this by creating a small Delphi-application that took the path to the file I wanted to execute and executed it by the WinExec API, which just starts the childprogram but doesn’t wait for it to complete = the program completes and the PHP.exe completes the script. Problem solved!
Delphi-snippet:
WinExec(PChar( ),SW_SHOW); // replace with the program path.
I was stuck for about an hour and a half last night trying to get Perl to pass back values to my PHP script after running an exec() command.
Of course, this wasn’t working and I finally figured it out with the help of a friend (Shawn = superstar): you need to echo the exec() command in order to get the values back into PHP.
In case you ever had to chain from php to another program (e.g. with a cgi php that only gives part of the output, or with php-gtk), here is a little C program that kills his parent (php, for instance), then launches a program given in argument.
Just following up my previous post, in reply to lancelot—du-lac at hotmail dot fr:
The behaviour described was fixed in PHP 5.3 in the following commit:
To replicate the fix in your own code, so it also runs on PHP 5.2, instead of:
= «. any shell command, maybe with multiple quotes. » ;
Within Linux, when calling the php interpreter directly from popen, or other program execution function to execute a script, it appears as though the script perpetually fails and re-executes.
[One solution is] to ensure the executing script has a valid shebang, and execute permissions. This allows you to execute the script directly
I found this comment on this page:
Instead of nslookup I believe this would apply to most programs from the \system32\ directory.
. but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory «c:\php\safedir\» is set in the php.ini setting
safe_mode_exec_dir = «c:\php\safedir\»
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!
Hope this helps somebody saving some time and headaches.
[end of quote]
This is just to complicated. Only two things are needed:
1. Specific permissions for the IUSR account for read & execute to the cmd.exe in C:\Windows\System32 directory
2. Specific permissions for the IUSR account for read & execute to the command that’s needed (example: nslookup.exe in C:\Widnows\System23 directory)
With just this two conditions the exec works fine
(This is for an IIS server running on a windows platform)
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.