'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 1:[1]
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
Solution 2:[2]
You can use strlen to get the number of bytes.
$stream = fopen('php://temp','r');
$content = stream_get_contents($stream);
$num_bytes_in_stream = strlen($content);
check this question: What the correct way to get size of binary data in php?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
