Jump to content

Archived

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

The Little Guy

Write binary data to a file

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?

Share this post


Link to post
Share on other sites

I would have gone for fwrite($handle, $string); and cut out the middle man.

Share this post


Link to post
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?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Basically, I want to try and write my own Database (mostly for kicks and giggles). So the table, I was hoping to make it look like an encrypted binary file. Maybe I am going about this the wrong way though...

 

What do you suggest?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

×

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.