Question

What I need is an equivalent for PHP's fseek() function. The function works on files, but I have a variable that contains binary data and I want to work on it. I know I could use substr(), but that would be lame - it's used for strings, not for binary data. Also, creating a file and then using fseek() is not what I am looking for either.

Maybe something constructed with streams?

EDIT: Okay, I'm almost there:

$data = fopen('data://application/binary;binary,'.$bin,'rb');

Warning: failed to open stream: rfc2397: illegal parameter

Was it helpful?

Solution

Kai:

You have almost answered yourself here. Streams are the answer. The following manual entry will be enlightening: http://us.php.net/manual/en/wrappers.data.php

It essentially allows you to pass arbitrary data to PHP's file handling functions such as fopen (and thus fseek).

Then you could do something like:

<?php

$data = fopen('data://mime/type;encoding,' . $binaryData);

fseek($data, 128);
?>

OTHER TIPS

fseek on data in a variable doesn't make sense. fseek just positions the file handle to the specified offset, so the next fread call starts reading from that offset. There is no equivalent of fread for strings.

Whats wrong with substr()?

With a file you would do:

$f = fopen(...)
fseek($f, offset)
$x = fread($f, len)

with substr:

$x = substr($var, offset, len)

I'm guessing, but maybe what is being asked for is a way to access bytes in a variable by using a pointer.. (using it like an array of bytes like you could do in c - without the memory overhead of putting the data in php arrays) and being able to edit them inplace without the overhead of copying the data.

Not being able to do this is a BIG problem, but if the operating system caches disk data well using fseek on a temporary file could be a workaround.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top