3

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 :(

nowox
  • 25,978
  • 39
  • 143
  • 293
  • I don't know much about openSSL, but there is [openSSL](http://php.net/manual/en/ref.openssl.php) extension in PHP. Is it not enough for your use case? – Dharman Jan 24 '19 at 21:11
  • Thanks, I know this, but this is not what my question is about, tags are `php` and `popen`, not `openssl` :) – nowox Jan 24 '19 at 21:18
  • 1
    Possible duplicate of [how get the output from process opend by popen in php?](https://stackoverflow.com/questions/15988369/how-get-the-output-from-process-opend-by-popen-in-php) –  Jan 29 '19 at 22:21
  • @Chipster, this is not a duplicate. Look at the title of my question. I want to pipe STDIN to a command and get the result from STDOUT. the question you linked does not address this problem. – nowox Jan 30 '19 at 15:23

1 Answers1

-1

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.

ivanivan
  • 2,155
  • 2
  • 10
  • 11