Jump to content

Write binary data to a file


The Little Guy

Recommended Posts

Is this the correct way to write binary data to a file?

 

$string = 'this is a string';
$handle = fopen('b.dat', 'wb');
for($i=0;$i<strlen($string);$i++){
    $hx = bin2hex($string{$i});
    fwrite($handle, pack("H*", $hx));
} 

 

If so, how do I read it an convert it back to a string?

If it is not correct, how do I do it?

Link to comment
https://forums.phpfreaks.com/topic/217687-write-binary-data-to-a-file/
Share on other sites

I don't think I understand what you are trying to do.  You can use fwrite() to write any string directly to a file, including strings containing what I would call "binary data".  Do you want to encode the string somehow before writing it?  If so, what encoding do you want to use?

Yeah, but what is your goal here. You have an ascii string in your example.  Are you just trying to obfuscate the data?  You could convert to base64 or something like that if you wanted to accomplish that.  Usually people use these functions because they have to move data back and forth from php and some application that has a specific data format.

Aha.. then you're looking for either obfuscation or encryption.  If it's just for fun you could use mcrypt() with a basic algorithm like 3DES in ECB mode.  That keeps things simple.  Except that the decrypted data is padded with null bytes up to the block size of the algorithm used - you'll need to remove those bytes after decrypting.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.