6

I'm trying to read from the php://memory wrapper using fread() but fread() always returns false. My code is simplified:

$file_handle = fopen('php://memory', 'w+'); // Have tried php:temp also.
fwrite($file_handle, 'contents');
$file = fread($file_handle, filesize($file_handle)); // Have also tried 99999 for filesize.

$file always is false after the fread().

What's going on?

Thanks in advance!

Shog9
  • 156,901
  • 35
  • 231
  • 235
jimmy
  • 504
  • 8
  • 16

4 Answers4

11

You'll need to rewind($file_handle) after writing before you can read what you've just written, because writing moves the file pointer to the end of the file

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
3

Call rewind($file_handle) before fread()

glennsl
  • 28,186
  • 12
  • 57
  • 75
1

Found the answer here: https://stackoverflow.com/a/2987330/2271704

I need to call rewind($file_handle) before I call fread().

Community
  • 1
  • 1
jimmy
  • 504
  • 8
  • 16
0

You should be getting this:

Warning: filesize() expects parameter 1 to be string, resource given

And those are the the first problem:

int filesize ( string $filename ) —  Gets the size for the given file.

... and the second one: you haven't enabled error reporting.

Third problem is that your pointer is at the end of the file. Try something like this:

error_reporting(E_ALL);
ini_set('display_errors', true);
// ...

rewind($file_handle);
$file = ''; //
while (!feof($file_handle)) {
    $file .= fread($file_handle, 8192);
}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Ahh yes, you are correct, filesize() does expect a file name, in my original code I was using strlen(). And again you are correct, I do have to rewind()! – jimmy Apr 19 '13 at 22:01