Main menu

Possible PHP file-to-memory mapping technique

Published by dnovikov on Sun, 07/10/2011 - 15:36

As widely known, PHP doesn't support direct access to file-to-memory mapping techniques. Here is one I've discovered while working with large character-separated files:

<?php
$mh
= fopen('php://memory', 'w+b');
ftruncate($mh, 33554432); //"allocate" 32Mb's of memory
rewind($mh);

$fname = 'yourfilename';

$fh = fopen($fname, 'r');
stream_copy_to_stream($fh, $mh, 33554432, 0); //copy 32Mb's window from the disc file

fclose($fh);
?>

Now you're free to work with memory handler $mh just like you do with any other regular file.

This approach will work only with PHP version >= 5.1.

However, note that you can reach very similar results with simple file_get_contents call. The main difference is that file_get_contents returns string, but memory mapping allows to use regular file functions.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.