views:

373

answers:

2

Hi,

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

+4  A: 

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);
?>
aaronmccall
This would work provided that allow_url_fopen is on in php.ini
Ionuț G. Stan
The code is invalid. The construct seems to be wrong. I did put 'rb' mode, but the first part seems to be wrong some way. "failed to open stream: rfc2397: illegal parameter in"
rFactor
See http://www.faqs.org/rfcs/rfc2045.html for allowed types
Peter Olsson
+1  A: 

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)
Craig
That is very slow. I'm dealing with large binary files. That's not what substr() was meant for.
rFactor
I'm confused now. Is the binary data in a file or in a php variable. If a file why not use fseek?
Craig
Sorry. The data is from a file that it gets from a transmission (not an upload form -- I could fseek the temp file, not filesystem -- I can't use fseek or doens't make sense to create files for that).
rFactor