Home » Software » Reading Files Without Filehandle PHP

Reading Files Without Filehandle PHP

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

  1. file_get_contents() function
  2. file() function
  3. readfile() function

Reading-Files-Without-Filehandle-PHP Reading Files Without Filehandle PHP

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.

file_get_contents() Format

Example of using file_get_contents() function

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.

file() format

Example of using file() function

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.

readfile() Format

Example of using readfile() function

That’s it, you can use one of three functions above to reading files without filehandle in PHP. If you got errors when trying to use it maybe you can check for common errors or debug it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.