If the php://temp
(or php://memory
) file is opened more than once, will the handles point to the same file? Or will each handle be unique?
I couldn't find an answer in the php docs, so I'm going to write up a test script to find out. I figured it's worth asking here so someone else can find the answer easily.
Each handle points to an independent stream. Example:
$a = fopen('php://memory', 'w+');
$b = fopen('php://memory', 'w+');
fwrite($a, 'foo');
fwrite($b, 'bar');
rewind($a);
rewind($b);
$a_text = stream_get_contents($a); //=> "foo"
$b_text = stream_get_contents($b); //=> "bar"
fclose($a);
fclose($b);
This is not explicitly documented anywhere, but it is implicit in the documentation for streams and wrappers.
From the official php documentation on streams in general, it is clear that for the standard case of streams, each file handle is associated with it's own independent stream.
And in the documentation on IO stream wrappers, it lists the possible wrappers noting exceptions as they occur. There is an exception listed for the first three (stdin, stdout, stderr):
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected.
But no such exception is listed for php://temp
or php://memory
. Hence it follows that these would work like normal independent streams.
Also, there are some comments on these pages that further imply the Independence of these streams.
My test code:
$f1 = fopen('php://temp', 'rw');
$f2 = fopen('php://temp', 'rw');
fputs($f1, "File One");
fputs($f2, "File Two");
rewind($f1);
echo "First line from F1: ";
echo fgets($f1) . PHP_EOL;
echo "Second line from F1: ";
echo fgets($f1) . PHP_EOL;
fclose($f1);
rewind($f2);
echo "First line from F2: ";
echo fgets($f2) . PHP_EOL;
echo "Second line from F2: ";
echo fgets($f2) . PHP_EOL;
fclose($f2);
And results:
First line from F1: File One
Second line from F1:
First line from F2: File Two
Second line from F2:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With