Replace HEX value within the file using fwrite php

59 Views Asked by At

i am trying to modify HEX Value within file using PHP on a specific offset.

$Offset1 = 30; //Offset 30 in the file
$valueinhex = dechex(90); //New value 90 in dec

$fh = fopen($current_file, 'wb');
fseek($fh, $Offset1);
fwrite($fh,$valueinhex);
fclose($fh);

My problem is that file gets viped out with everything and untill offset1 there are 00's offset1 is 90 and this is eof. Like fseek doesn't work at all.

I think problem is in fwrite that it writes only my value and not current_file+value hmm

Thanks

-EDIT-
Let me re-write the question :

I have File1.bin which has content:
01 02 03 04 05 06 07 08 09 0A

i want to edit 6th byte in this file to
01 02 03 04 05 FF 07 08 09 0A

and save it as File2.bin```
1

There are 1 best solutions below

0
Thomas Miller On

Solution here:

$current_file = "File1.bin";
$newfile = "File2.bin";
$Offset1 = 30;
$valueinhex = dechex(90);

$fh = fopen($newfile, 'wb+');
rewind($fh);
$content = file_get_contents($current_file, false, NULL, 0, filesize($current_file));
fwrite($fh, $content);

fseek($fh, $Offset1);
fwrite($fh, pack('H*', $valueinhex), 2);
rewind($fh);

fclose($fh);

Everything works :)