php exec вывод результата

Вывод в реальном времени результатов выполнения shell_exec в PHP

Для чтения вывода процесса используется popen(). Она позволяет PHP скрипту работать параллельно с определённой программой и даёт возможность взаимодействовать с ней, читать и записывать во вывод/ввод программы будто бы в файл.

Допустим, мы хотим запустить в операционной системе, где установлен веб-сервер, такую команду:

Тогда в PHP скрипте мы присваиваем переменной значение, которое будет отправлено в ОС для выполнения в качестве команды:

Если мы хотим просто получить результат и вывод в реальном времени нас не интересует, тогда можно использовать passthru():

Но если вы хотите отображать вывод в реальном времени пока работает программа, то можно сделать так:

Этот код запустит команду и будет отправлять пользователь её вывод в реальном времени.

Подсказки использования shell_exec

Не всегда работает:

Похоже, в примере выше, разрыв строки вывода gunzip препятствует shell_exec напечатать что-либо ещё.

Быстрое напоминание тем, что пытается использовать shell_exec в UNIX-подобных платформах и не может заставить работать свой скрипт. В системе PHP делает запуск программ как веб-пользователь (обычно www, www-data или http для Apache), поэтому вам нужно убедиться, что веб-пользователь имеет достаточно прав для файлов, директорий или программ, которые вы пытаетесь использовать в команде shell_exec. В противном случае, будет казаться, что ничего не происходит.

Скорее всего неправильным (и точно опасным), но рабочим способом является добавление Apache прав запускать программы от имени суперпользователя без пароля.

Для Debian (и производных вроде Kali Linux, Linux Mint, Ubuntu) это делается так:

В файл /etc/sudoers

Для Arch Linux / BlackArch это делается так:

Добавить (раскомментировать) строчку:

Помните, что shell_exec() does не захватывает STDERR (стандартный вывод ошибок), поэтому используйте «2>&1» для его перенаправления в STDOUT (стандартный вывод) и захвата.

Простой способ захватить STDERR (стандартный вывод ошибок) и отбросить STDOUT (стандартный вывод) это добавить ‘2>&1 1> /dev/null‘ к концу вашей команды

Как shell_exec, так и обратная кавычка (`) возвращают NULL, если выполняемая команда не выводит что-либо.

Это позволяет нам делать примерно такие трюки:

Здесь мы просто выводим пустой пробел если команда завершилась успешно, что удовлетворяет это слегка странной проблеме. Отсюда вы можете использовать trim() для вывода команды.

Ошибка Subversion «svn: Can’t recode string» может быть вызвана неправильной (отсутствующей) локалью (locale). Попробуйте

(или любую другую локаль, какую вы предпочитаете) перед вызовом shell_exec()

Источник

Выполнить команду оболочки в PHP с помощью exec()

Главное меню » Программирование » PHP » Выполнить команду оболочки в PHP с помощью exec()

php exec вывод результата. Смотреть фото php exec вывод результата. Смотреть картинку php exec вывод результата. Картинка про php exec вывод результата. Фото php exec вывод результата

Синтаксис:

Эта функция может принимать три аргумента. Первый аргумент является обязательным, который примет системную команду. Два других аргумента необязательны. Второй аргумент используется для хранения вывода команды в массиве. Третий аргумент этой функции используется для хранения статуса возврата выполненной команды. Эта функция возвращает последнюю строку из вывода выполненной команды.

Пример-1: Использование функции exec () без дополнительных аргументов

Пример-2: Распечатать все значения выполненной команды

Пример-3: Распечатать все файлы PHP в текущем каталоге

Пример-4: Запуск сценария bash

Как любой сценарий bash может быть выполнен с помощью функции exec (), показано в этом примере. Создайте файл bash с именем loop.sh со следующим скриптом, который будет печатать все четные числа от 1 до 20.

Следующий вывод появится после запуска вышеуказанного скрипта с сервера. Вывод показывает все четные числа от 1 до 20.

Пример 5: Запуск команды `dir` с помощью функции exec()

Заключение:

В этой статье были объяснены различные варианты использования функции exec(), чтобы помочь кодировщикам PHP узнать способ выполнения команды оболочки с помощью сценария PHP. Некоторые другие функции также существуют в PHP для выполнения задач того же типа.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Функции запуска программ

Примечания

Открытые файлы с блокировкой (особенно открытые сессии) должны быть закрыты до выполнения программы в фоне.

Смотрите также

Эти функции также тесно связаны с оператором обратные кавычки («).

Содержание

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.

Источник

PDO::exec

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::exec — Выполняет SQL-запрос и возвращает количество затронутых строк

Описание

PDO::exec() запускает SQL-запрос на выполнение и возвращает количество строк, задействованных в ходе его выполнения.

Список параметров

SQL-выражение, которое необходимо подготовить и запустить.

Данные внутри запроса должны быть правильно экранированы.

Возвращаемые значения

Примеры

Пример #1 Выполнение запроса DELETE

Получение количества удалённых записей запросом DELETE без условий WHERE.

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 6 notes

PDO::eval() might return `false` for some statements (e.g. CREATE TABLE) even if the operation completed successfully, when using PDO_DBLIB and FreeTDS. So it is not a reliable way of testing the op status.

PDO::errorInfo() can be used to test the SQLSTATE error code for ‘00000’ (success) and ‘01000’ (success with warning).

For those that want an exec that handles params like prepare/execute does. You can simulate this with another function

If you are wondering about the fetch after, remember some databases can return data SELECT-like data from REMOVE/INSERTS. In the case of PostgreSQL, you can have it return you all records that were actually removed, or have the insert return the records after the insert/post field functions, and io trigger fire, to give you normalized data.

You can’t use it not only with SELECT statement, but any statement that might return rows. «OPTIMIZE table» is such example (returns some rows with optimization status).

If you do, PDO will lock-up with the «Cannot execute queries while other unbuffered queries are active.» nonsense.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *