S
S
sorry_i_noob2018-11-20 04:43:02
PHP
sorry_i_noob, 2018-11-20 04:43:02

A few questions about the fopen function?

Hello.
The manual page for the fopen function says...

On the Windows platform, you must escape all backslashes in the file path, or use forward slashes.

I wrote this code (without escaping characters) and it works great:
<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

$fopen_result_1 = fopen('folder\file.txt', "a+");
$content_1 = fread($fopen_result_1, filesize('folder\file.txt'));
echo $content_1;

echo '<br><br><br><br>';

$fopen_result_2 = fopen('folder/file.txt', "a+");
$content_2 = fread($fopen_result_2, filesize('folder/file.txt'));
echo $content_2;

Why does it work? And no error is thrown. It was the first question.
Question two. The manual says...
Since setting the default translation flag depends on SAPI and the PHP version you are using, we recommend that you explicitly set the specified flag for portability reasons. You should use the 't' mode if you are working with text files and use \n to mark the end of a line in your script, but expect your files to be used in applications such as Notepad. In all other cases, use the 'b' flag.

And then...
Note:
For portability reasons, it is highly recommended to always use the 'b' flag when opening files with fopen().

Note:
In addition, for portability reasons, it is also highly recommended to rewrite old code that relies on 't' mode to use proper line endings and 'b' mode instead.

First it says that 't' should be used when opening text files, and 'b' when opening binary files. And then - ALWAYS USE 'b'. So what to use? Unclear. Can you explain?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2018-11-20
@sorry_i_noob

1) you need to escape if after the slash comes n, t or r. Because \r \n \t are special characters. Your code works because there are other characters after the slash. In order not to force you to remember these special characters, they suggest escaping everything. True, this is only relevant if the path is in double quotes. those. "folder\nile.txt".
2) don't use t. when using it and running the script on Windows, when writing to a file, \n will be replaced with \r\n. In order for the standard notepad to open normally. Naturally, this is nonsense (as well as using this notebook).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question