Dan Lugg
Dan Lugg

Reputation: 20592

php://memory & php://temp; preserving stream data on subsequent handle creation

This question is closely related to my new findings, regarding this question.

Is there any way to preserve the in stream data of php://memory or php://temp between handles? I read (somewhere I can't source off hand) that subsequent openings of the aforementioned streams clears existing data.

$mem1 = fopen('php://memory', 'r+');
fwrite($mem1, 'hello world');
rewind($mem1);
fpassthru($mem1); // "hello world"

$mem2 = fopen('php://memory', 'r+');
rewind($mem2);
fpassthru($mem2); // empty

So again my question is, is there anyway to force existing data to persist in stream when creating a new handle to it?

(The latter call to fpassthru() would of course dump hello world given this is possible)

Upvotes: 1

Views: 4475

Answers (3)

oriadam
oriadam

Reputation: 8559

The handlers are unique, so you'll have to pass the handler, or (god forbid) keep the handler global

$GLOBALS['my_global_memory_stream']=fopen('php://memory','r+');

Upvotes: 0

Rafał Wrzeszcz
Rafał Wrzeszcz

Reputation: 2057

If you need in-memory virtual stream that persists data you can use https://github.com/mikey179/vfsStream - although it's mainly used for testing I/O operations it should fulfill your requirements - it stores data within internal objects which are identified by virtual URLs so you can access same data in memory by accessing same URL.

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 131881

Opening one of the pseudo-streams php://temp or php://memory always opens a new stream, what means, that every stream your open this way is unique. So you can't read the content of the stream you have previously written to another one.

Upvotes: 6

Related Questions