3

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.