Php system function call

system

system() похожа на C-версию этой функции в том, что она выполняет указанную команду command и выводит её результат.

Вызов функции system() также пытается автоматически очистить буфер вывода веб-сервера после каждой строки вывода, если PHP работает как модуль сервера.

Если вам нужно выполнить команду и получить все данные из команды непосредственно без каких-либо препятствий, используйте функцию passthru() .

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

Команда, которая будет выполнена.

Если есть аргумент return_var , то код возврата выполняемой команды будет записан в эту переменную.

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

Возвращает последнюю строку вывода команды в случае успеха, и FALSE — в случае неудачи.

Примеры

Пример #1 Пример использования system()

// Выводит весь результат шелл-команды «ls», и возвращает
// последнюю строку вывода в переменной $last_line. Сохраняет код возврата
// шелл-команды в $retval.
$last_line = system ( ‘ls’ , $retval );

// Выводим дополнительную информацию
echo ‘


Последняя строка вывода: ‘ . $last_line . ‘


Код возврата: ‘ . $retval ;
?>

Примечания

Если вы собираетесь передавать функции пользовательские данные, используйте функции escapeshellarg() или escapeshellcmd() для того, чтобы пользователи не смогли обмануть систему, запустив произвольную команду.

Замечание:

Если вы собираетесь использовать эту функцию в программе, работающей в качестве демона, убедитесь, что стандартный вывод функции направлен в файл или другой поток, в противном случае PHP зависнет вплоть до конца выполнения программы.

Замечание: В случае работы в безопасном режиме, вы можете запускать что-либо только в пределах safe_mode_exec_dir. В настоящее время по практическим причинам запрещено использование .. в качестве компонента пути к исполняемому файлу.

В случае работы в безопасном режиме, строка с командой экранируется с помощью escapeshellcmd() . Таким образом echo y | echo x становится echo y \| echo x.

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

  • exec() — Исполняет внешнюю программу
  • passthru() — Выполняет внешнюю программу и отображает необработанный вывод
  • popen() — Открывает файловый указатель процесса
  • escapeshellcmd() — Экранирует метасимволы командной строки
  • pcntl_exec() — Executes specified program in current process space
  • оператор «обратный апостроф»

Источник

PHP exec() vs system() vs passthru()

What are the differences? Is there a specific situation or reason for each function? If yes, can you give some examples of those situations? PHP.net says that they are used to execute external programs. see reference From the examples I see, I don’t see any obvious difference. If I were to simply run a script (bash or python), which function do you recommend me to use?

There’s also proc_open() and popen() , both of which allow a higher degree of control over the spawned process.

5 Answers 5

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output — presumably text.
  • passthru() is for executing a system command which you wish the raw return from — presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

Sometimes portability has to be sacrificed for functionality. There are some things PHP just can’t do well.

@Kalium: can you elaborate more on your statement? just stating some vague percentage statistics does not convince me. I believe that using system calls to execute scripts are totally fine as long as the whole application does not depend one a bunch of scripts in the back-end.

@Kalium «. 95% of the time people want to use a shell call, the reasons are all wrong. » I think is very subjective this approach, would you mean all programmers, devops, sysadmins should think the same way, do the same thinks on the same path?. Where is freedom?. I think there is no «Wrong» approach, but rather there are «Better» ways to deal every specific problem.

Also, it’s a fallacy to think that PHP is portable as long as you avoid exec , system , passthru . PHP code is reliant on the environment it runs in, and many security bugs are due to not having this in consideration. Here’s a quick example: stackoverflow.com/questions/3003145/…

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences.

+----------------+-----------------+----------------+----------------+ | Command | Displays Output | Can Get Output | Gets Exit Code | +----------------+-----------------+----------------+----------------+ | system() | Yes (as text) | Last line only | Yes | | passthru() | Yes (raw) | No | Yes | | exec() | No | Yes (array) | Yes | | shell_exec() | No | Yes (string) | No | | backticks (``) | No | Yes (string) | No | +----------------+-----------------+----------------+----------------+ 
  • «Displays Output» means it streams the output to the browser (or command line output if running from a command line).
  • «Can Get Output» means you can get the output of the command and assign it to a PHP variable.
  • The «exit code» is a special value returned by the command (also called the «return status»). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add «2>&1» to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn’t empty, it will append the new output to it. So you may need to unset($output) first.

@johnywhy none per se — unless you explicitly invoke the php cli or such. I suppose you want include and friends

The system() Function

The system function in PHP takes a string argument with the command to execute as well as any arguments you wish passed to that command. This function executes the specified command, and dumps any resulting text to the output stream (either the HTTP output in a web server situation, or the console if you are running PHP as a command line tool). The return of this function is the last line of output from the program, if it emits text output.

The exec() Function

The system function is quite useful and powerful, but one of the biggest problems with it is that all resulting text from the program goes directly to the output stream. There will be situations where you might like to format the resulting text and display it in some different way, or not display it at all.

For this, the exec function in PHP is perfectly adapted. Instead of automatically dumping all text generated by the program being executed to the output stream, it gives you the opportunity to put this text in an array returned in the second parameter to the function:

The shell_exec() Function

Most of the programs we have been executing thus far have been, more or less, real programs1. However, the environment in which Windows and Unix users operate is actually much richer than this. Windows users have the option of using the Windows Command Prompt program, cmd.exe This program is known as a command shell.

The passthru() Function

One fascinating function that PHP provides similar to those we have seen so far is the passthru function. This function, like the others, executes the program you tell it to. However, it then proceeds to immediately send the raw output from this program to the output stream with which PHP is currently working (i.e. either HTTP in a web server scenario, or the shell in a command line version of PHP).

The proc_open() Function and popen() function

proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP’s end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.

Источник

Читайте также:  Питон двумерный массив задачи
Оцените статью