开发者

Having problems reading/writing the php://temp stream

开发者 https://www.devze.com 2023-03-03 22:15 出处:网络
I\'m having trouble with reading a开发者_运维问答nd writing the php://temp stream in PHP 5.3.2

I'm having trouble with reading a开发者_运维问答nd writing the php://temp stream in PHP 5.3.2

I basically have:

file_put_contents('php://temp/test', 'test');
var_dump(file_get_contents('php://temp/test'));

The only output I get is string(0) ""

Shouldn't I get my 'test' back?


php://temp is not a file path, it's a pseudo protocol that always creates a new random temp file when used. The /test is actually being ignored entirely. The only extra "arguments" the php://temp wrapper accepts is /maxmemory:n. You need to keep a file handle around to the opened temp stream, or it will be discarded:

$tmp = fopen('php://temp', 'r+');
fwrite($tmp, 'test');
rewind($tmp);
fpassthru($tmp);
fclose($tmp);

See http://php.net/manual/en/wrappers.php.php#refsect1-wrappers.php-examples


Each time, when you use fopen to get handler, content of php://temp will be flushed. Use rewind() and stream_get_contents() to get content. Or, use normal cachers, like APC or memcache :)


Finally found a documented small note, that explains why

Example 5 at the PHP Manual used almost your exact same code sample and says

php://memory and php://temp are not reusable, i.e. after the streams have been closed there is no way to refer to them again.

file_put_contents('php://memory', 'PHP');
echo file_get_contents('php://memory'); // prints nothing

I guess this means that file_put_contents() closes the stream internally, which makes file_get_contents() unable to recover the data in the stream again


I know this is late, but in addition to @OZ_'s answer, i just discovered that 'fread' works too, after you rewind.

$handle = fopen('php://temp', 'w+');

fwrite($handle, 'I am freaking awesome');

fread($handle); // returns '';

rewind($handle); // resets the position of pointer

fread($handle, fstat($handle)['size']); // I am freaking awesome
0

精彩评论

暂无评论...
验证码 换一张
取 消