Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real binary write PHP

Tags:

php

binary

How do I do something as simple as (in PHP) this code in C:

char buffer[5] = "testing";
FILE* file2 = fopen("data2.bin", "wb");
fwrite(buffer, sizeof buffer, 1, file2);
fclose(file2);

Whenever I try to write a binary file in PHP, it doesn't write in real binary.

Example:

$ptr = fopen("data2.bin", 'wb');

fwrite($ptr, "testing");

fclose($ptr);

I found on internet that I need to use pack() to do this...

What I expected:

testing\9C\00\00
or
7465 7374 696e 679c 0100 00

What I got:

testing412

Thanks

like image 296
Maurício Giordano Avatar asked Dec 02 '25 23:12

Maurício Giordano


1 Answers

You're making the classic mistake of confusing data with the representation of that data.

Let's say you have a text file. If you open it in Notepad, you'll see the following:

hello
world

This is because Notepad assumes the data is ASCII text. So it takes every byte of raw data, interprets it as an ASCII character, and renders that text to your screen.

Now if you go and open that file with a hex editor, you'll see something entirely different1:

68 65 6c 6c 6f 0d 0a 77 6f 72 6c 64          hello..world

That is because the hex editor instead takes every byte of the raw data, and displays it as a two-character hexadecimal number.

1 - Assuming Windows \r\n line endings and ASCII encoding.


So if you're expecting hexadecimal ASCII output, you need to convert your string to its hexadecimal encoding before writing it (as ASCII text!) to the file.

In PHP, what you're looking for is the bin2hex function which "Returns an ASCII string containing the hexadecimal representation of str." For example:

$str = "Hello world!";
echo bin2hex($str);      // output:  48656c6c6f20776f726c6421

Note that the "wb" mode argument doesn't cause any special behavior. It guarantees binary output, not hexadecimal output. I cannot stress enough that there is a difference. The only thing the b really does, is guarantee that line endings will not be converted by the library when reading/writing data.

like image 88
Jonathon Reinhart Avatar answered Dec 05 '25 13:12

Jonathon Reinhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!