Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string to hex/bytes?

Im trying to edit the bytes of a file. More like a hex viewer/editor. For example:

//Adding the file bytes to array (byte array)
$bytes = str_split(file_get_contents("test.file")); //It can be any file. like jpg,png, exe, jar...

And now i want just to edit 5 bytes and change them to some chracter values. For example:

//Adding the file bytes to an array (byte array)
$bytes = str_split(file_get_contents("test.file")); //It can be any file. like jpg,png, exe,jar...

$string = "hello";

$bytes[5] = $string[0];
$bytes[6] = $string[1];
$bytes[7] = $string[3];
$bytes[8] = $string[4];

file_put_contents("edited.file", $bytes);

But it just doesnt work... I need to convert first the letters of the $string to bytes and then edit the specific bytes of the byte array ($bytes), without corrupting the file.

I have tried using unpack(), pack() functions but i cant make it work... I have tried also ord() function but then saves them as interger, but i want to save the bytes of the string.

like image 620
user2493164 Avatar asked Jan 29 '26 19:01

user2493164


1 Answers

It sounds like you might need to be using unpack to read out the binary data and then pack to write it back.

According to the documentation this would be roughly what you would want. (However YMMV as I have never actually done this for myself.)

   <?php
       $binarydata = file_get_contents("test.file");
       $bytes = unpack("s*", $binarydata);
       $string = "hello";
       $bytes[5] = $string[0];
       $bytes[6] = $string[1];
       $bytes[7] = $string[3];
       $bytes[8] = $string[4];
       file_put_contents("edited.file", pack("s*", $bytes));
   ?>

According to the notes the array that unpack produces starts it's index at 1 rather than the more normal 0. Also I cannot underscore strongly enough that I've not tested the suggestion at all. Treat it like an educated guess at best.

More Info: http://www.php.net/manual/en/function.unpack.php

More Info: http://www.php.net/manual/en/function.pack.php

like image 193
Matthew Brown aka Lord Matt Avatar answered Jan 31 '26 09:01

Matthew Brown aka Lord Matt