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
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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.