Searching a sequence of bytes in a binary file in PHP?
First of all your $mysequence
is not changing while search, so you can call hex2bin($mysequence)
once and compare it with $seq
directly.
As for doing it really faster, you can try read and search for string in large buffers. Larger buffer => faster search, but more memory needed. Fast code draft, how this should look like:
$mysequence = "4749524f";
$searchBytes = hex2bin($mysequence);
$crossing = 1 - length($searchBytes); // - (length - 1); see below
$buf = ''; $buflen = 10000;
$f = fopen($filename, "r") or die("Unable to open file!");
while(!feof($f))
{
$seq .= fread($f, $buflen);
if(strpos($seq, $searchBytes) === false) // strict comparation here. zero can be returned!
{
// keep last n-1 bytes, because they can be beginning of required sequence
$seq = substr($seq, $crossing);
}
else
{
echo "found!";
break;
}
}
unset($seq); // no need to keep this in memory any more