Page 1 of 1

how to open pipe for writing and then read its output?

Posted: Wed Feb 25, 2004 9:17 am
by vasilis
Here is the main part of my gnupg encryption function for encrypting text contained in the '$plain_text' variable and outputting it to the '$encrypted_text' variable:

Code: Select all

$command =  "$gpg -a --recipient " . ""$public_key_id"" . " --encrypt";
$pipe=popen($command, "w");
$no_ofbytes_written=fwrite($pipe, escapeshellarg($plain_text));
$encrypted_text = '';
while($s = fgets($pipe, 1024)) {  
 $encrypted_text .= $s;
 }
 pclose($pipe);
return $encrypted_text;
I have checked the code and I know that a number of bytes is written to the pipe (the '$plain_text' variable content is written in the pipe, since I get non-zero return from the fwrite() function - $no_ofbytes_written<>0). SO, I guess the encryption works ok. The problem is that I cannot read from the pipe with the fgets() function, since it has been opened with the "w" argument. If I try to open it for reading (with "r" argument), the 'fgets()' function writes zero bytes to it . Therefore, I need to find a way to re-open the same pipe for reading (and of course keep its contents) (i dont want to use physical files since they are insecure for pgp encryption of sensitive data).
Can anybody help me to that ??? In a few words, how can you open a pipe for writing, write to it, and then read from it ??

Posted: Wed Feb 25, 2004 4:13 pm
by evilMind
do you have safe mode enabled?

Posted: Thu Feb 26, 2004 8:14 am
by vasilis
Does safe mode have to do with the above? I have checked that code and it works ok, anyway in my local computer. My question is, again, how do I open a pipe for writing, feed it with input, and read its output ??

Posted: Thu Feb 26, 2004 8:22 am
by evilMind
Yes. Safe mode *does* have to do with the above. Safe mode can cause your pipes to behave uncommonly. eg: grep -Hi pattern * | cut -b 10- woud turn into grep -Hi pattern "* | cut -b -10-" having astonishingly different results then the aforementioned.

Posted: Fri Feb 27, 2004 12:35 pm
by vasilis
I do not have safe mode enabled, neither in my local testing computer, nor in the server where my account has been tested.
The thing is that regardless of safe mode, my question has a theoretical dimension... i.e. how one can open a pipe for writing, send to it some input, and then read the output from it to a variable... (since the pipe was opened for writing with the "w" parameter, then in order to read from it, shouldn't it be opened for reading (with "r" parameter)???. But, before openint it again for reading, shouldn't it be closed, an action that would mean losing its data???

Posted: Sat Feb 28, 2004 11:30 am
by Weirdan
pipes are uniderectional. use [php_man]proc_open[/php_man] instead.

Posted: Mon Mar 01, 2004 12:15 pm
by vasilis
thanks, that sounds like its gonna work... I ll try it out....