flaab
flaab

Reputation: 581

Can I edit a binary (hex) file with PHP, replace a string and save without corrupting the binary?

I have a little problem :)

  1. I have a binary file -executable- which I want to edit and replace a string
  2. I open the file with PHP, perform a replace and save it
  3. Saved binary is corrupt.

If I do it using SED or any hexadecimal editor, it works fine.

Can I open, edit (replace a string) and save a binary file using PHP?

Thank you very much!

Upvotes: 4

Views: 4050

Answers (2)

peter
peter

Reputation: 42207

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter. Then use fread and fwrite on the file.

<?php
$fp = fopen('binary_file.bin', 'w+b');
fwrite($fp, '1');
fclose($fp);
?>

Upvotes: 2

Tei
Tei

Reputation: 1416

You could read the file byte by byte, doing a binary comparation, and a byte to byte replacement. Write PHP code that look like C code :D

Upvotes: -2

Related Questions