jump to navigation

The right way to read local-remote files with PHP October 17, 2010

Posted by Tournas Dimitrios in PHP.

One of the joys of dealing with modern programming languages like PHP is the amount of options available. PHP could easily steal the Perl motto, “There’s more than one way to do it,” especially when it comes to file processing. But with the plethora of options available, what’s the best tool for the job? Of course, the real answer depends on your goal when parsing the file, so it’s worth the time to explore all your options. This article shows four ways to read from files . Actually the process is exactly the same no matter if the file is locally or remotely .The tools for reading files with PHP are :

  • fopen()
  • file_get_contents
  • file()
  • readfile()

Traditional fopen methods :

Fopen() is, for many, a fiendishly complex function to use. The reason for this is because it is another one of those functions lifted straight from C, and so is not as user-friendly as most PHP functions. On the flip-side, as per usual, is the fact that fopen() is an incredibly versatile function that some people come to love for its ability to manipulate files just as you want it to.

Fopen() has two key parameters: the file to open, and how you would like it opened. Parameter one is easy – it is just $filename, as with the other examples. Parameter two is what makes fopen() so special: you specify letters in a string that define whether you want to read from (“r”), write to (“w”), or append to (“a”) the file specified in parameter one. There is also a fourth option, “b”, which opens the file in binary mode. This is not necessary on Unix-based systems, but it is on Windows, so it is best to use it everywhere – it is not detrimental on Unix-based systems at all.

Fopen() returns a file handle resource, which is basically the contents of the file. You cannot output it directly, e.g. “print fopen(….)”, but fopen() -related functions all accept file handles as the file to work with, so you should store the return value of fopen() in a variable for later use. Therefore, here’s a full usage of fopen() :

Take a look at the following usages:

$filename = "localfile.txt";
$filename = "http://www.in.gr";
//The "x" parameter can be "r","w" or "a"
 $handle = fopen($filename, "x");

If the file cannot be opened, fopen() returns false. If the file is successfully opened, a file handle is returned and you can proceed.

Once the file handle is ready, we can call other functions on the opened file, depending on how the file was opened (the second parameter to fopen() ). To read from a file, the function fread() is used, and to write to a file fwrite() is used. For now we’re interested in reading, so you should use “rb” for the second parameter to fopen().

Fread() takes two parameters: a file handle to read from (this is the return value from fopen(), remember) and the number of bytes to read. The second parameter might not make sense at first, after all you generally want to read in all of a file, right?

Author’s Note: Do not worry about specifying a number in parameter two that is larger than the file – PHP will stop reading when it hits the end of the file or the number of bytes in parameter two, whichever comes first.

So, to use fread() to read in an entire file, we can use the following line:

 $contents = fread($handle, filesize($filename));

Well, while the chances are that you will indeed want to read in all of a file, doing so requires you have enough memory to be able to read in the entire file at once – if you are working with files of several megabytes or indeed hundreds of megabytes, PHP’s resource consumption would balloon. In circumstances such as these you have but two choices: buy more RAM, or parse your data sequentially!

Luckily, most people will not have to make that choice – most people work with text files under a megabyte in size, and PHP can load a megabyte file all at once in a tiny fraction of a second. To instruct PHP to use fread() to read in the entire contents of a file, you simply need to specify the exact file size in bytes of that file as parameter two to fread(). Sound difficult? PHP comes to the rescue again with the filesize() function, which takes the name of a file to check, and returns its filesize in bytes – precisely what we’re looking for.

When reading in a file, PHP uses a file pointer to determine which byte it is currently up to – kind of like the array cursor. Each time you read in a byte, PHP advances the array cursor by one place – reading in the entire file at once advances the array cursor to the end of the file.
Notice that fread() ‘s return value is the text it read in, and in above situation that is the entire file. To finish off using fread() it is simply necessary to close the file as soon as you are done with it. To close a file you have opened with fopen(), use fclose() – it takes the file handle we got from fopen(), and returns true if it was able to close the file successfully. We have now got enough to use fopen() to fully open and read in a file, then close it. Here is the script:

    $handle = fopen($filename, "rb");
    $contents = fread($handle, filesize($filename));
    print $contents;

file_get_contents() :

File_get_contents () is similar to fread () in that it returns the entire contents of the file to a single string, however it can be done in a single line and performs better then fread ().

 $filestring = file_get_contents($filename);
 print $filestring;

Using fgets () in PHP :

Fgets () is used to read the data from a file one line at a time starting from the pointer. It defaults to only reading the first 1024 bytes of a line, however you can set this variable higher or lower if you wish. If your file is not separated with line breaks, this is not the right function to use.


$file_handle = fopen("dictionary.txt", "r");

while (!feof($file_handle)) {

$line_of_text = fgets($file_handle);
print $line_of_text . "<BR>";





Using file () in PHP :

File () is similar to fgets in that it reads the data one line at a time, however it returns it all at once into an array. The array contains the line number, and the data corresponding to each line number starting with 0. If you want to do more than simply echo the data, having it in an array will provide much more flexibility making file () more useful than fgets ().

 $lines = file('YourFile.txt');
 foreach ($lines as $line_num => $line) {
 print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n";


What this code does first is put the contents of YourFile.txt into the array called $lines. It then enters into a loop which prints each line number in red, followed by the line contents, and repeats until all lines have been printed.

readfile() :

If you want to output a file to the screen without doing any form of text processing on it whatsoever, readfile() is the easiest function to use. When passed a filename as its only parameter, readfile() will attempt to open it, read it all into memory, then output it without further question. If successful, readfile() will return an integer equal to the number of bytes read from the file.

If unsuccessful, readfile() will return false, and there are quite a few reasons why it may file. For example, the file might not exist, or it might exist with the wrong permissions.

Here is an example script:


The first example will work on most Unix-like systems, and will attempt to open the file test.txt in Paul’s home directory – you will almost certainly want to change this to point to somewhere that exists and you have access to. The second example is for Windows systems, and should work in any Windows NT-descended OS, including Windows XP and Vista.

The advantages to using readfile() are clear: there is no fuss, and there is little way for it to go wrong. However, the disadvantage is equally clear: you have got absolutely no control over the text that comes out.

You should use readfile() when you just want to print a file out without any further action on your behalf – it is a powerful little one-liner.


1. PHP Basics: Accessing Remote URLs using cURL « Tournas Dimitrios - October 17, 2010

[…] The 4 file manipulation functions (aka fopen(), file_get_contents() , file() , readfile() ) see this article . […]

2. Jon Hoffmann - July 9, 2012

I was attracted to you text because of the term “local file”, but I am not sure how you define “local file”. It seems like a file on the server where the PHP script is executed? It is not local to the browser?

tournasdimitrios1 - July 9, 2012

The term “local” , defines a file(s) on the server where PHP is executed . PHP can only access files on the server where it’s installed ( if it has permissions to do so ) . It can also access publicly available files from other servers (Web , FTP and File-servers) .
For security reasons , even client-side scripting languages (JavaScript , Flash , Silverlight , Java-applets ) are restricted to access only a couple files on visitor’s computers (Normal HTTP cookies , Flash cookies ) .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s