PHP.mk документација

passthru

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.passthru.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.passthru.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
passthru

Референца за `function.passthru.php` со подобрена типографија и навигација.

function.passthru.php

passthru

(PHP 4, PHP 5, PHP 7, PHP 8)

passthruИзврши надворешна програма и прикажи го суровиот излез

= NULL

passthru(string $command, int &$result_code = null): ?false

На passthru() функцијата е слична на exec() функцијата со тоа што извршува command. Оваа функција треба да се користи наместо exec() or system() кога излезот од Unix командата е бинарни податоци што треба директно да се вратат до прелистувачот. Честа употреба за ова е извршување на нешто како pbmplus комуналните услуги што можат директно да излезат со стрим на слика. Со поставување на Content-type на image/gif и потоа повикување на pbmplus програма за излез на gif, можете да креирате PHP скрипти што директно излегуваат слики.

Параметри

command

наместо за такви случаи.

result_code

Ако result_code аргументот е присутен, статусот на враќање на Unix командата ќе биде поставен овде.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. null на успех или false при неуспех.

Errors/Exceptions

Ќе емитува E_WARNING if passthru() не може да го изврши command.

Фрла ValueError if command е празно или содржи нулти бајти.

Дневник на промени

Верзија = NULL
8.0.0 Враќа command е празно или содржи нулти бајти, passthru() сега фрла ValueError. Претходно емитуваше E_WARNING и врати false.

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Кога дозволувате кориснички податоци да се предадат на оваа функција, користете escapeshellarg() or escapeshellcmd() за да се осигурате дека корисниците не можат да го измамат системот да изврши произволни команди.

Забелешка:

Ако програма се стартува со оваа функција, за да продолжи да работи во позадина, излезот од програмата мора да биде пренасочен до датотека или друг излезен поток. Неуспехот да се направи тоа ќе предизвика PHP да чека додека не заврши извршувањето на програмата.

Види Исто така

Белешки од корисници — Интерпретира стринг од XML во објект

puppy на cyberpuppy dot org
21 години пред
Regarding swbrown's comment...you need to use an output buffer if you don't want the data displayed.

For example:
ob_start();
passthru("<i>command</i>");
$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.
jo на durchholz dot org
пред 18 години
Note to Paul Giblock: the command *is* run through the shell.
You can verify this on any Linux system with

<?php
passthru ('echo $PATH');
?>

You'll get the content of the PATH environment variable, not the string $PATH.
igor на bboy dot ru
20 години пред
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=\"myfile.zip\"");
header("Content-Length: 11111");
passthru("cat myfile.zip",$err);

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

exit();

after the passthrough. This will exit the script after the download is done and will not interfere with any future actions.
divinity76+spam на gmail точка com
3 години пред
if you have problems with passthru("docker-compose ...bash") losing interactive shell size information, try using proc_open instead, for some reason docker-compose bash knows the size of the outer terminal when i use use proc_open, but loses that information when i use passthru,

eg i replaced
<?php
passthru("docker-compose -f docker-compose.yml bash",$ret);
?>
with
<?php
$empty1=array();
$empty2=array();
$proc=proc_open("docker-compose -f docker-compose.yml bash",$empty1,$empty2 );
$ret = proc_close($proc);
?>

and suddenly docker-compose bash knew my terminal size :)
Зак Естрада
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).
Стујарт Ив
20 години пред
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';

passthru($command);

It only worked once I put:

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

passthru($command);
mail на dtrasbo dot dk
3 години пред
To capture the output of a command in a string without using output buffer functions, use shell_exec()
tox на novasonica dot com
пред 6 години
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.
myselfasunder на gmail dot com dot dfvuks
пред 15 години
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
(PHP 4, PHP 5, PHP 7, PHP 8)
пред 17 години
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.
sarel dot w на envent dot co dot za
21 години пред
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.
swbrown на ucsd dot edu
пред 22 години
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.
nuker на list dot ru
20 години пред
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)

<?php
function getProxyFromIE()
{
        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyEnable",
        $proxyenable,$proxyenable_status);

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

        if($proxyenable_status!=0)
        return false; #Can't access the registry! Very very bad...
        else
        {
        $enabled=substr($proxyenable[4],-1,1);
        if($enabled==0)
        return false;
        else
        {
        $proxy=ereg_replace("^[ \t]{1,10}ProxyServer\tREG_SZ[ \t]{1,20}","",
        $proxyserver[4]);

        if(ereg("[\=\;]",$proxy))
        {
             $proxy=explode(";",$proxy);
             foreach($proxy as $i => $v)
             {
                   if(ereg("http",$v))
                   {
                   $proxy=str_replace("http=","",$v);
                   break;
                   }
             }
             if(@!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:".
             "[0-9]{1,5}$",$proxy))
             return false;
             else
             return $proxy;
        }
        else
        return $proxy;
        }

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

Usage:
<?php
$proxy=getProxyFromIE();
if(!$proxy)
echo "Can't get proxy!";
else
echo $proxy;
?>
kpierre на fit dot edu
figroc at gmail dot com
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...

#!/bin/sh
exec 2>&1
ulimit -t 60
cat nosuchfile.txt
stuartc1 на NOSPAM dot hotmail dot com
20 години пред
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().
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.