how to rewind() an http stream file in PHP other than fclose() and fopen() again?

4.3k Views Asked by At

PHP's fopen lets you fopen() http locations as file streams.
But you can't fseek() or rewind() them, is there a way to accomplish this other than fclose() and fopen() it again?

3

There are 3 best solutions below

1
On BEST ANSWER

The others mentioned it: PHP doesn't support fseek() and rewind() on non-local streams. I suggest you download/cache the file and interact with that. For example

$cache = fopen('php://temp', 'r+');
stream_copy_to_stream($remoteResource, $cache);

Now you should be able to do with $cache whatever you have done with $remoteResource before, except that you are now able to seek within (and therefore also rewind) it. If you close the temp-stream PHP will automatically cleanup any used resources.

2
On

For starters, you shouldn't be using f____ functions to open remote files. That is what curl is for.

I don't believe there is a way to reset/rewind a pointer on a remote socket, so unless PHP's file functions buffer and cache the data in the stream, I don't see how they could allow you to rewind the pointer.

I could be wrong, though...I'm no socket expert.

1
On

Quoting from the PHP docs

Note:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail

As with fseek(), the rewind() function may not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.