Page 1 of 1
Fastest way to get a byte at a position from a file?
Posted: Fri Mar 20, 2009 11:18 am
by kaisellgren
Hello,
I have data of over a megabyte. I need to get specific bytes from it (at specific positions). Eg position 165604. I was going to use arrays until I realized that PHP is imcapable of handling an array of 1024*1024 rows...
I need this to be as efficient as possible.
Do you got any ideas? My current idea is to read $pos bytes from the file then use substr($data,$pos,1)...
Re: Fastest way to get a byte at a position from a file?
Posted: Fri Mar 20, 2009 11:52 am
by Mark Baker
open the file, use fseek() to set your position, then read the data at that position
No need to read any additional data
Re: Fastest way to get a byte at a position from a file?
Posted: Fri Mar 20, 2009 11:53 am
by kaisellgren
Mark Baker wrote:open the file, use fseek() to set your position, then read the data at that position
No need to read any additional data
Indeed, that's pretty fast

Re: Fastest way to get a byte at a position from a file?
Posted: Fri Mar 20, 2009 12:01 pm
by php_east
Code: Select all
$filename = "myveryveryverylargefile.jpg";
$filesize = filesize($filename);
$handle = fopen($filename, "r");
$contents = fread($handle, $filesize);
fclose($handle);
/* read 100 bytes, start at 165604 */
$span = 100;
$offset = 165604;
echo implode (' ',unpack ("@$offset/C$span", $contents));
die();
move backwards forwards and change window size as you wish by changing offset and span
( more at
http://www.phpdig.net/ref/rn45re878.html )
p/s btw , absolutely no idea how this measures up with pos or seek, i'd be interested which is fastest. if you exclude file load time ( assuming you already have the data ), then i think this is fastest.