Monday, June 29, 2020

How to Read a File In PHP

There are two ways to read whole content of a file in PHP language. First way is to use the function fread() with the function filesize(). The second way is to use the function file_get_content().

Examples

The following code shows how to use the first method.
$path = "C:\Users\XUser\documents\my-file.txt";
$stream = fopen($path, 'r');
$wholeContent = fread($stream, filesize($path));
fclose($stream);

The following code shows how to use the first method.
$path = "C:\Users\XUser\documents\my-file.txt";
$stream = file_get_content($path);

As for me, I recomend the second way over the first one. Because in some cases, I have seen that the first way does not read the whole file. In addition, it is easier to understand than the first one

No comments:

Post a Comment

Feel free to write any thing in your mind here 😉