6.6 Handling Binary Data Safely


You want to handle a binary file, but your data keeps getting mangled.

Technique

Although fopen() is binary-safe (using the b flag), you have to use fread() and fwrite() when accessing binary files instead of using functions such as fputs() and fgets() .

Good:
 $fp = @fopen($fn, "ab+")   or die ("Cannot open $fn in 'ab+' mode"); fwrite ($fp, "This is a binary safe file write"); fseek ($fp, 0); $f_contents = fread ($fp, filesize($fp)); @fclose ($fp); 
Bad:
 $fp = @fopen ($fn, "a"); fputs ($fp, "This is not Binary Safe"); fseek ($fp,0); while ($line = @fgets($fp, 1024)) {     print "reading line by line, not binary safe...\n"; } @fclose ($fp); 

Comments

If your systems don't distinguish between binary and text files (like UNIX), you don't have to worry about placing the "b" in the mode for fopen() . However, this syntax is important for systems such as Windows, which distinguish between binary and text files. Therefore, if you are writing for portability, use the "b" even if you will be using the script on a UNIX box.

fwrite() and fread() are both binary-safe, meaning that they don't mangle your binary data. However, functions such as fputs() and fgets() are not binary safe. Therefore, even if you open your file with the "b" flag, there is still a possibility that your binary data will be messed up in the translation.

When handling binary data in PHP, there are some functions that will support it and some functions that will mangle it. As a general rule, I suggest that you test and retest your script for all possible cases when you are handling binary data.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net