go top


  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

Reading files with PHP

Tuesday, 6th December, 2011  /  PHP Tutorials  /  5 Comments
Today we will start a series of tutorials about file manipulations. The series will include file reading and writing. Then we will see how to copy, move or delete a file. We will also go through directory creation and listing. Latter we will review change of user/group rights of both files and folders and renaming. Of course our tutorial will include a lot of examples, that most of the time make reading the text around them needless.

Today's tutorial is about file reading and writing. It is separated in two parts named surprisingly File Reading and File Writing.

First of all you must make sure that you have permissions. This is a complex subject that includes FileSystem permissions, PHP restrictions and also Apache HTTP server configuration. For the purpose of our tutorial I assume that you have them set. Let's go then. The starting point of every file operation is getting a file handle that will point to our file. This is done by using fopen() function.

// Open Unix file
$handle = fopen("/home/phpjabbers/somefile.txt", "r");
// Open Windows file. Mind that you have to escape the backslashes or I advise you to use forward slashes.
$handle = fopen("c:\data\info.txt", "rt");
$handle = fopen("c:/data/info.txt", "rt");

There are several ways to open the file, they are called modes, and it all depends on what you want to do with it. If you just want to deal with already existing file and you do not want to delete it's content you have to use the following two modes:

r - opens the file for reading only and places the cursor at the beginning of the file.
r+ - opens the file for reading and writing and places the cursor at the beginning of the file.

If you want to create a new file or replace the existing one you have to use one of the following two modes:

w - opens the file for writing only and places the cursor at the beginning of the file. If the file exists it empties it's contents (truncates the file to zero length). It the file does not exist, it makes an attempt to create it.
w+ - the same as above only that this time the file is open for reading also.

Another two writing modes allow us different approach:

a - opens the file for writing only and places the cursor at the end of it. If the file does not exist, attempt to create it.
a+ - opens the file for reading and writing and places the cursor at the end of it. If the file does not exist, attempt to create it.

The last two modes are used when we want to create a file.

x - create a file and open it for writing only. This mode places the file pointer at the beginning of the file. An important notice about this mode is that, if the file already exists, the function will fail and will return FALSE.
x+ - the same as above but create and open the file for reading also.

IMPORTANT: When working with files on Windows based operating systam there are two more modes that you must know. They are combined with the other file open parameters.

t - is used when you are working with text files. What is does is translate your line ending characters (n to rn).
b - this mode must be used when working with non-text files. It is strongly recommended that you use b flag when opening files on Windows. If you don't you might experience strange problems with your file.

Now that we have our file we can start working with it.

PART 1 - FILE READING ( examples included )

First we will focus on reading files. There are several way to do it. We will start with reading text files. Most of the time we need to read our file line by line. For this operation we use this function - file(); It reads the entire file into array.

file() - Reads text file into an array.

// file example
$lines = file("/tmp/files/InputTextFile.txt");
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . $line . "n";

As you can see it is very simple to output text file content. What more can we add here. Just that file() supports a few optional parameters:

FILE_USE_INCLUDE_PATH - Search for the file in the include_path.
FILE_IGNORE_NEW_LINES - Do not add newline at the end of each array element(in our case $line).
FILE_SKIP_EMPTY_LINES - Skip empty lines.

A similar function that reads the entire content of a file, but this time to a string is file_get_contents(). It supports two additional parameters, which sometimes can be very helpful: offset and maxlen bytes (they were added in PHP 5.1). Offset specifies where to start reading from, and maxlen specifies how many bytes to read from the source. This function is binary safe.

file_get_contents() - Reads entire file into a string. It also shows how to read 1KB starting at the 128th byte.

// file_get_contents example
$file = file_get_contents("/tmp/files/InputTextFile.txt",0,null,128,1024);
echo $file;

Here is another example this time reading remote file.

// file_get_contents example
$file = file_get_contents("http://www.example.com/tmp/files/InputTextFile.txt");
echo $file;

More direct way to print the file to the buffer is readfile() function. What is does is just that. You do not even have to echo it. It returns the bytes that have been read.

readfile - Outputs the entire file to the output buffer

// readfile() example
$file = "/tmp/files/InputTextFile.txt";
$bytesRead = readfile($file);
echo $bytesRead;

The next function that can help us reading a file is fgets(). It reads a line starting from the file pointer position and returns it as a string. You can also specify the length of bytes you want it to read. If you tend to use it, have in mind, that reading file ends when length - 1 bytes have been read, a newline is reached, or EOF is reached (whichever comes first). This function requires file handle to operate with. In our example we read our file in 8KB chunks at most.

fgets() - Gets a line from file pointer

// fgets example
// Windows OS
$file = "c:/tmp/files/InputTextFile.txt";
$handle = fopen($file, "rt");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 8192);
echo $buffer;

The last function that we will take a look at and show an example of it is fread(). It is used to read binary files. It takes a file handle and reads length bytes from the file pointer. Reading file ends when length bytes or 8192 bytes (8KB) have been read,
end of file (EOF) is reached or when a packet becomes available (for network streams), whichever comes first.

fread() - Binary-safe file read

// fread example
$file = "/tmp/files/picture.gif";
// REMEMBER: If this is Windows OS you have to use "rb"
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));

This example shows how you can read binary files from the web.

$handle = fopen("http://www.example.com/picture.gif", "r");
$contents = '';
while (!feof($handle)) {
$contents = $contents . fread($handle, 8192);

It is not much of a use to print the contents of a binary file, but it you want to write it to a new file this function is the way to do it.
Share on:

5 Comments to "Reading files with PHP"

Hire Php Website Developer

Hire Php Website Developer / August 10, 2017 at 09:35 am

Great tutorial!! This was a great tutorial with lots of good examples and resources. I absolutely like this tutorial.



Honey / December 21, 2015 at 12:14 pm

How to read word doc/docx file

Chandrakant Pawar

Chandrakant Pawar / December 8, 2013 at 14:38 pm

Dear Friend

following is the coding thro which i want to open pdf file, which will asked by input command.

File: <input type="text" name="file">
<input type="submit" value="Display">
<a href=&file>click here to open pdf</a>

I have to enter the file name (mostly pdf) in the 4th line and
5th line should open the same file.

what will be the syntax of the 5th line

Please suggest the coding, i am stuck up there.


Ali / May 5, 2012 at 11:00 am

Hi, thanks for this useful tutorial, but i cant read pdf or doc file like this code

$handle = fopen("http://www.example.com/picture.gif", "r");
$contents = '';
while (!feof($handle)) {
$contents = $contents . fread($handle, 8192);

This code produces output as ansi text for pdf or doc files.
Do you know a method for reading pdf or doc file content?


Parimal / June 23, 2011 at 20:16 pm

It is great & very much helpful for developer and designer as well.

Add your comment


    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team

    Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.

    Free scripts

    PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!

    Commercial PHP scripts