Search code examples
phpio

How to get the size of a temp stream in PHP?


It seems like this ought to be really obvious, but I can't seem to find the answer anywhere. Assuming I create a stream using php://temp, how do I get the length of the data written?

$stream = fopen('php://temp', 'w+');
// ... do some processing here using fwrite, stream_copy_to_stream, stream_filter_append, etc ...
$num_bytes_in_stream = // What goes here? 

Solution

  • php://temp uses a temporary file. The file is empty as long as nothing has been written. fopen expects at least 2 parameters. Mode "w+" can also be used in this case.

    $stream = fopen('php://temp','r+');
    var_dump(fstat($stream)['size']);  //int(0)
    
    $r = fputs($stream,'1234');
    var_dump(fstat($stream)['size']);  //int(4)
    
    rewind($stream);
    $str = fgets($stream,'1234');
    var_dump($str, fstat($stream)['size']);  //string(4) "1234" int(4)
    

    Try self on https://3v4l.org/Hsodg