'PHP fopen() with "wb" not working

Here is a snippet of what I'm trying to do:

$file = fopen($path,  "wb");
fwrite($file, $data);
fclose($file);

Simple enough. But when I open the created file, I see 0x0D inserted before 0x0A everywhere. I understand that this will happen if I open the file without binary mode.

But I've clearly specified I want binary mode. Maybe my brain isn't functioning right or something, so.. Anyone got a solution?



Solution 1:[1]

It turns out, for some weird reason, the problem was with my $path. My $path value was "temp".

It would generate the file named "temp" but would refuse to open it in binary mode. Giving the file an extension like "temp.bin" or "temp.tmp" allowed it to work in binary mode.

Problem solved for now but I'm still wondering why it works like this.

Solution 2:[2]

Seems the problem is with the $path. Please make sure you have given the correct file path.

If you are defining the $path with a dynamic file name, use / before the file name. For example, $var = "/var/www/html/projectFolder/folderFile/". "Filename.fileformat"

If you're working with URLs in a redirection context, then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives.

Solution 3:[3]

You're making the classic mistake of confusing data with the representation of that data.

Let's say you have a text file. If you open it in Notepad, you'll see the following:

$str = "Hello world!";
echo bin2hex($str);      // output:  48656c6c6f20776f726c6421

$file = fopen($path,  "wb");
$data = bin2hex($data);
fwrite($file, $data);
fclose($file);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Justin AnyhowStep
Solution 2 Varun P V
Solution 3 Shailesh Katarmal