Search code examples
phppopen

How to execute an external program, sending data to STDIN and capturing STDOUT?


In my PHP script I have a variable $pkcs7_bin that I would like to transform through openssl.

Assuming I have my input in a file, I could do this with bash:

cat in.pkcs7 | openssl pkcs7 -inform DER > out.pkcs7

I would like to do the same in PHP such as:

$exit_status execute('openssl pkc7 -inform DER', $pkcs7_bin, $pkcs7_out);

Of course I do not want to use intermediate files.

Is this a simple way to do it?

Currently I have written this:

function execute($process, $stdin, &$stdout)
{
    ob_start();
    $handle = popen($process, 'w');
    $write = fwrite($handle, $stdin)
    &$stdout = ob_get_clean();
    pclose($handle);
}

But I realized that what the output flushed on my screen is not captured by ob_start :(


Solution

  • For generic use for console commands, what you are after is shell_exec() - Execute command via shell and return the complete output as a string

    Note that for your use case, the OpenSSL functions that PHP provides may do what you need to do "natively" without worrying about spawning a shell (often disabled for security reasons)

    Anyway, back to shell_exec():

    cat in.pkcs7 | openssl pkcs7 -inform DER > out.pkcs7

    could be done as // obtain input data somehow. you could just // shell_exec your original command, using correct // paths to files and then read out.pkcs7 with file_get_contents() $infile=file_get_contents("/path/to/in.pcks7"); $result=shell_exec("echo ".$infile." | openssl pcks7 - inform DER");

    May/will/does need tweeking with " and ' to handle special characters in the $infile content. Change $infile to be whatever input you'd be sending anyway, just be sure to quote/escape properly if needed.