Reading a file without using a filehandle is possible especially in PHP. Because PHP provides functions that allow you to read the contents of a file without opening it. In this article, we will discussed 3 functions to accessing a file without filehandle. They are
- file_get_contents() function
- file() function
- readfile() function
How to read a file into a string without using filehandle
To read a file without using a filehandle you can use file_get_contents() Function. It can read the whole file into a string. By opening file without using a filehandle, will improve your web application performance. All you need is just pass the name of the file to the function file_get_contents() and it will get the contents of the whole file and save it in string. It can also start reading from a specified offset and even can specify how many bytes you want to read. The PHP Manual and most expert programmer suggest this as the most efficient way to read a file into a string.
1 string file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen ]]]])
Example of using file_get_contents() function
1 $content = file_get_contents("etechnologytips.txt");
That’s an example of how to read whole file into a string. If you want to know how to read whole file into an array. you can use PHP’s file() function.
Reading a file into an array
You can read an entire file into an array with PHP’s file() function without using a filehandle. The filename can be a full path or url. The function returns FALSE if it fails executing. You can use rtrim() function if you don’t want the end-of-line character at the end of each array elements. This function (file()) is identical to file_get_contents() . The only difference is it returns the file in an array.
1 array file (string filename [, int use_include_path [, resource context]])
Example of using file() function
12 $filepath="$_SERVER[DOCUMENT_ROOT]/../mydir/file";$lines = file($filepath);
Output of variable $lines is an array. To manage content of $lines you can use array functions explode() and implode().
The readfile() function to reading and writing file
If you want to reads from a file and writes it to the output buffer, readfile() function will do. readfile() returns the number of bytes read from the file. If it failed on executing or error occurs, FALSE is returned and diagnostic message is printed.
1 int readfile (string filename [, bool use_include_path [, resource context]])
Example of using readfile() function