readfile()

int readfile ( string filename [, bool use_include_path [, resource context]])

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:

<?php
    readfile("/home/paul/test.txt");
    readfile("c:\\boot.ini");
?>

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.

Note that from here on in I will be using the variable $filename to signify a filename you have chosen. This is to avoid having to keep printing separate examples for Windows and Unix.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: file_get_contents() and file() >>

Previous chapter: Reading files

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.