In reading the documentation for php fopen for php I see the following:
For portability, it is strongly recommended that you always use the 'b' flag when opening files with fopen().
What is the b
flag and what does it do ?
Why is it strongly recommended ?
The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created.
The fopen() function opens the file that is specified by filename . The mode parameter is a character string specifying the type of access that is requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.
The 'b' flag forces binary mode.
You use the 'b' flag if you want to deal with binary files, ie. an image.
Note:
When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system.
Unix based systems use
\n
as the line ending character, Windows based systems use\r\n
as the line ending characters and Macintosh based systems use\r
as the line ending character.Windows offers a text-mode translation flag ('t') which will transparently translate
\n
to\r\n
when working with the file.In contrast, you can also use 'b' to force binary mode, which will not translate your data.
You can avoid the translation by using the 'b' flag in the mode
parameter. Example usage:
$handle_read = fopen($filepath, 'rb');
$handle_write = fopen("/home/user/file.gif", "wb");
So... the reason this is recommended is clearly stated on the manual:
If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.
The usage of 'b' flag is also noted on manual pages of fwrite()
and fread()
which are binary-safe file read/write functions.
Warning:
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With