6 Ways to Read Files In PHP – Into String, Array, And More!

Welcome to a tutorial on how to read files in PHP. Yep, that is right, how difficult can reading files in PHP be? You will be surprised… It is not as straightforward as some may think.

There are quite a number of ways to read files in PHP:

  1. Read file into a string – $contents = file_get_contents("FILE");
  2. Read file into an array – $array = file("FILE");
  3. Use cURL to fetch a file from a different server.
    • $curl = curl_init("http://site.com/");
    • curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    • $data = curl_exec($curl);
    • curl_close($curl);
  4. Open a file stream and read line-by-line.
    • $stream = fopen("FILE", "r");
    • while(($line=fgets($stream))!==false) { echo $line; }
  5. Read and directly output – readfile("FILE");
  6. Directly load a file into the script – include "FILE"; require "FILE";

That is a quick overview of the common methods, but let us walk through some examples in this guide – Read on!

ⓘ I have included a zip file with all the sample code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Read Files Summary & Links
Tutorial Video The End

 

 

DOWNLOAD & NOTES

First, here is the download link to all the example codes.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

READ FILES IN PHP

All right, let us now get into the various ways to read files in PHP.

 

1) READ FILE INTO A STRING

1-file-to-string.php
<?php
// (A) READ ENTIRE CONTENTS INTO A STRING
$text = file_get_contents('README.txt');
echo $text;
 
// (B) ALSO CAN FETCH FROM URL
$text = file_get_contents('https://en.wikipedia.org/wiki/Aha_ha');
echo $text;

There is not much rocket science involved here, just take note that file_get_contents() can fetch contents from a file or URL. While this is straightforward, take extra care to not read massive files with this… You will run into an “out of memory” error, and possibly cause some issues on the server.

 

 

2) READ FILE INTO AN ARRAY

2-file-to-array.php
<?php
// (A) FILE TO ARRAY
$array = file('README.txt');
print_r($array);
 
// (B) ADDITIONAL OPTION - SKIP EMPTY LINES
$array = file('README.txt', FILE_SKIP_EMPTY_LINES);
print_r($array);

This is another simple one. But instead of a flat string, file() will read into an array instead, with each element being a different line. Take note again, do not attempt to read large files with this.

 

3) CURL FETCH

3-curl.php
<?php
$curl = curl_init("https://en.wikipedia.org/wiki/Aha_ha");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
echo $data;

CURL stands for “client URL”, and in layman’s term “server-to-server calls”. Some of you guys may be thinking – What the heck, isn’t this a roundabout way of doing file_get_contents()? Well no. CURL actually offers a lot of options and controls – It can even fetch files from an FTP server. Will leave the reference links below if you are interested.

 

 

4) READ FILE LINE-BY-LINE

4-line-by-line.php
<?php
// (A) OPEN FILE
$handle = fopen("README.txt", "r") or die("Error reading file!");
 
// (B) READ LINE BY LINE
while (($line = fgets($handle)) !== false) {
// To better manage the memory, you can also specify how many bytes to read at once
// while (($line = fgets($handle, 4096)) !== false) {
  echo $line;
}
 
// (C) CLOSE FILE
fclose($handle);

The above 3 methods will run into a memory problem when dealing with large files. So to deal with that problem, we can use fgets() and read line-by-line instead.

 

5) FILE STREAM

5-file-stream.php
<?php
// (A) START OUTPUT BUFFER
ob_start();
 
// (B) HTTP HEADERS TO FORCE DOWNLOAD
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="README.txt"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize('README.txt'));
 
// (C) OUTPUT ALL THE HEADERS & STOP BUFFERING
ob_end_flush();
 
// (D) READ AND OUTPUT FILE DIRECTLY
readfile('README.txt');
exit();

This next method is a little different from the rest. Instead of reading a file into strings and arrays, it directly outputs it. Very useful when it comes to forcing a download or transferring huge files.

 

 

6) INCLUDE OR REQUIRE

6-include-require.php
<!DOCTYPE HTML>
<html>
<body>
  <?php
  require "README.txt";
  ?>
</body>
</html>

You have probably heard of include and require since day 1 of learning PHP – Yes, they can be used for any file type actually.

 

SUMMARY & LINKS

That’s all for this guide, and here are some extras and links that may be useful.

 

THE SUMMARY

Function Description Reference
$STRING = file_get_contents(FILE OR URL); Reads file into a string. Click Here
$ARRAY = file(FILE); Reads file into an array, separated by line breaks. Click Here
$CURL = curl_init(URL); Initializes CURL. Click Here
curl_setopt($CURL, OPTION, VALUE); Set the cURL options. At the bare minimum, we have to set CURLOPT_RETURNTRANSFER to retrieve data. Click Here
$DATA = curl_exec($CURL); Execute CURL. Click Here
curl_close($CURL) Close the CURL connection. Click Here
$HANDLE = fopen(FILE, "r"); Opens a file stream. Click Here
while ($LINE = fgets($HANDLE)) { ... } Read line-by-line. Click Here
fclose($HANDLE); Close the file stream Click Here
readfile(FILE); Read and directly output file. Click Here
require FILE Load specified file/script – Throws an error and halt if the file cannot be opened. Click Here
include FILE Load specified file/script – Throws a warning but will not halt if the file cannot be opened. Click Here

 

 

YOUTUBE TUTORIAL

 

THE CHEAT SHEET

Ways to Read Files in PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope this has helped to solve your file reading yoga issues, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “6 Ways to Read Files In PHP – Into String, Array, And More!”

  1. Saša Živković

    there is an error in example 4: Open a file stream and read line-by-line.

    $stream = fopen(“FILE”, “r”);
    while(($line=fgets($handle))!==false) { echo $line; }

    instead of $handle there should be $stream!

Leave a Comment

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