(PHP 4, PHP 5, PHP 7)

passthruВыполняет внешнюю программу и отображает необработанный вывод


void passthru ( string $command [, int &$return_var ] )

Функция passthru() похожа на функцию exec() в том, что она выполняет команду command. Эта функция должна быть использована вместо функции exec() или system() когда вывод команды Unix является двоичными данными, которые необходимо передать непосредственно в браузер. Стандартное использование этой функции - выполнить команду, такую, как утилиты pbmplus, которые выводят непосредственно поток изображения. Установив Content-type в image/gif и затем вызвав программу pbmplus для вывода gif-рисунка, вы можете создать PHP-скрипты, которые выводят изображения непосредственно в браузер.

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


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


Если присутствует аргумент return_var, то код возврата Unix-команды будет помещён здесь.

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

Эта функция не возвращает значения после выполнения.



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


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

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


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

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


About the problem of zombies, you may call a bash script like this:

#! /bin/bash
ulimit -t 60

<your command here>
2001-02-14 19:06:20
PJ's ulimit example is nice; however, if you include multiple commands in the script after the ulimit command, each gets its own, seperate 60 second time slot!<br>

Furthermore, these sixty seconds are *CPU* time. Most programs hang for other reasons than CPU hogging (for example, waiting for a database connection) so for most purposes the number 60 is rather too high.<br>

Try "ulimit -t 1" first, which will give you about 10^9 cycles on modern hardware -- quite enough to get a lot of work done!
2001-06-20 20:25:17
If you sometimes get no output from passthru() use system() instead. This solved this problem for me (php 4.0.5 on Tru64 Unix compiled with gcc).
2001-10-03 10:51:30
The documention does not mention that passthru() will only display standard output and not standard error.

If you are running a script you can pipe the STDERR to STDOUT by doing 

exec 2>&1

Eg. the script below will actually print something with the passthru() function...

exec 2>&1
ulimit -t 60
cat nosuchfile.txt
2002-01-30 09:35:54
passthru() seems absolutely determined to buffer output no matter what you do, even with ob_implicit_flush().  The solution seems to be to use popen() instead.
2003-06-03 23:41:27
With apache 2.x on RH9 passthru() writes 1 byte at a time. Apache 2.x buffers and chunk encodes the output for you - but the chunked encoding devides the output in chunks of 1 byte each...thus several bytes of overhead per byte. I guess that buffering behaviour is by design - but caused problems for me with IE adobe acrobot 5 plugin. The plugin doesn't like like it if you send it a stream of 1 byte chunks - it tells you your file is not a pdf or gives a blank screen. Using output buffering (ob_start / ob_endflush) gives reasonable size chunks and the plugin works OK.
2003-09-04 14:23:30
Regarding kpierre's post, be mindful that if you shell script errors, you will find the error output from it in the base error_log file (not virtualhost error_log) in apache.
2004-05-27 11:30:31
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).
2004-12-14 10:21:39
Regarding swbrown's need to use an output buffer if you don't want the data displayed.

For example:
$var = ob_get_contents();
ob_end_clean(); //Use this instead of ob_flush()

This gets all the output from the command, and exits without sending any data to stdout.
2005-03-02 16:50:50
Zak Estrada
14-Dec-2004 11:21 
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).

Remember, you'll also get this error if your file does not have executable permission.
2005-03-09 01:33:55
If you are using passthru() to download files (for dynamically generated content or something outside webserver root) using similar code:

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"\"");
header("Content-Length: 11111");

and your download goes fine, but subsequent downloads / link clicks are screwed up, with headers and binary data being all over the website, try putting


after the passthrough. This will exit the script after the download is done and will not interfere with any future actions.
2005-06-23 16:33:35
Thought it might beuseful to note the passthru seems to supress error messages whilst being run in Dos on Windows (test on NT).

To show FULL raw output including errors, use system().
2005-08-09 10:52:56
I had an issue when i used exec

I think we were echoing information on the test.php script.
for eg: when we tried 

exec(php test.php,$array,$error);

the return was 127 and the code was failing.

checking the note on this page gave us a hint to use passthru instead.
The only thing to note is that you need to provide the fuull path.

now our command became

passthru(/bin/php /pathtotest/test.php,$array,$error);

this works.

2005-10-13 06:09:58
I dunno if anyone else might find this useful, but when I was trying to use the passthru() command on Suse9.3 I was having no success with the command:

$command = 'gdal_translate blahahahaha';


It only worked once I put:

$command = '/usr/bin/local/gdal_translate blalalala';

2005-12-08 13:24:35
I wrote function, that gets proxy server value from the Internet Explorer (from
registry). It was tested in Windows XP Pro

(Sorry for my English)

function getProxyFromIE()
exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
"\Windows\CurrentVersion\Internet Settings\" /v ProxyEnable",

exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
"\Windows\CurrentVersion\Internet Settings\" /v ProxyServer",

false#Can't access the registry! Very very bad...
$proxy=ereg_replace("^[ \t]{1,10}ProxyServer\tREG_SZ[ \t]{1,20}","",

$proxy as $i => $v)

Note, that this function returns FALSE if proxy is disabled in Internet
Explorer. This function returns ONLY HTTP proxy server.

"Can't get proxy!";
2006-01-03 07:51:52

The pasthru function does not execute the program through the shell.  What this mean, among other things, is that your PATH variable is never set.  Therefore, you have to use full paths on everything.

I believe system() will run your program underneith a shell.  This allow the program to run in a 'normal' environment.

2007-05-18 14:30:04
Note to Paul Giblock: the command *is* run through the shell.
You can verify this on any Linux system with

('echo $PATH');

You'll get the content of the PATH environment variable, not the string $PATH.
2007-11-22 14:17:54
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
2008-07-29 12:48:57
PHP's program-execution commands fail miserably when it comes to STDERR, and the proc_open() command doesn't work all that consistently in non-blocking mode under Windows.

This command, although useful, is no different. To form a mechanism that will see/capture both STDOUT and STDERR output, pipe the command to the 'tee' command (which can be found for Windows), and wrap the whole thing in output buffering.

Dustin Oprea
2010-11-29 15:00:13
`command` // back ticks drop you out of PHP mode into shell
exec('command', $output); // exec will allow you to capture the return of a command as reference
shell_exec('command'); // will return the output to a variable
system(); //as seen above.
2016-11-22 17:46:05
I was trying to implement a system that allows running arbitrary CLI commands with parameters, but I kept running into the issues with user prompts from the command as they would let execution hang. The solution is simple: just use passthru() as it outputs everything and correctly handles user prompts out of the box.
2019-09-03 13:57:09

    Поддержать сайт на родительском проекте КГБ