Search code examples
phphttpstreamfopenfseek

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


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?


Solution

  • 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.