Open a File with PHP

 

To open up a file, there are a few methods you can use. The one we'll start with is readfile( ). As it's name suggest, it reads the contents of a file for you. Try this simple script (this assumes that you've read the short introduction on the previous page).

<?PHP

$file_contents = readfile( "dictionary.txt" );
print $file_contents;

?>

Save the script with any file name your like, but make sure it goes in the same folder as your dictionary.txt file (see the previous page for an explanation of this file). Run your new code, and see what happens.

You should get a web page full of text, with no separation and no line breaks.

And that's it! Simple, hey? Only two lines of code. You can even get it down to one line:

print readfile("dictionary.txt");

But here's the part that does the reading:

$file_contents = readfile("dictionary.txt");

You start by typing readfile, and then a pair of round brackets. In between the round brackets, type the name of the file you want to open. This can be either direct text, as above, or a variable, like this:

$file_to_read = "dictionary.txt";
print readfile($file_to_read);

You don't have to put the file you're trying to read in the same directory. If you had a folder called files in your directory, you could do this:

$file_to_read = "files\dictionary.txt";
print readfile($file_to_read);

Or have any other file reference you want to use.

The readfile( ) function is useful if all you want to do is open up a file and read its contents.


file_get_contents(file_to_read);

Another function that just reads the contents of a file is file_get_contents( ). It is available in PHP version 4.3 and above. Here's an example:

<?PHP

$file_to_read = "dictionary.txt";
print file_get_contents( $file_to_read );

?>

This used in more or less the same way as the readfile function. The difference for us is the change of name to file_get_contents( ).

In the next part, we'll take a look at the more commonly used fopen function