简体   繁体   中英

How does passthru() work?

I am interested to know what exactly passthru() is doing?

I have to create my own function with similar functionality, but I cannot understand how the function works.

Why not using shell_exec and appending >> file to command?

function exec_to_file($cmd,$file){
    shell_exec(escapeshellcmd($cmd) . ' >> ' . $file);
}

Do you need to display binary data after executing a command?

How would you like to change to standard behaviour?

As far as I know passthru() works similar to exec() and system(), but allows for the processing/display of binary data as well, so my guess would be that it pipes the output from the passthru() command directly to a binary stream.

See http://php.net/manual/en/function.passthru.php .

I hope this helps, otherwise I deserve a down-vote.

The source to passthru can be found in ext/standard/exec.c - it's actually pretty readable and should be possible to write your own version in PHP directly.

It sounds like what you need to do is simply use popen to open a process, then you can just read output from it like any other file handle.

The internals of passthru won't help you much, since they're too low-level to be reproducible by PHP.

My goal is to forward the output to any arbitrary file, not just php://stdout.

If you want to do this on PHP level without first reading the whole output into a variable, I'd suggest something like popen . This lets you open a pointer to a process, from which you can read little by little and write the data to a file little by little (which is actually probably pretty close to what passthru does). Eg:

while (($buffer = fread($p, 1024)) !== false) {
    fwrite($file, $buffer);
}

If you're working on the command line anyway though, why not just write to a file there?

exec('command > file');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM