Working With Files In PHP

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. 

<?PHP
$file_contents = readfile( "dictionary.txt" );
print $file_contents;
?>

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( ).

A better method to open files is with fopen( ). This function gives you more options that, such as setting whether the file is for reading only, for writing to as well, and a few more options.

<?PHP
$file_contents = fopen( "dictionary.txt", "r" );
print $file_contents;
fclose($file_contents);
?>

Run this script and see what happens. You should see something like the following printed out:

Resource id #2

Not quite what you were expecting! The reason is that fopen( ) doesn't actually read the contents of a file. All it does is to set a pointer to the file you want to open. It then returns what's call a file handle. All you're doing is telling PHP to remember the location of the file.
The "r" on the end means "open this file for reading only". We'll see other options in a moment. But now that you've told PHP to remember the location of the file you want to open, how do you read the contents of the file?

One way is to use fgets( ). This will read a specified number of character on a single line of text. It's typically used to loop round and read each line of text. In the example below, we're printing out each line separately. When you're using fgets( ), you also need to check when the end of the file has been reached. This is done with the inbuilt function feof - file, end ofile. Try the script out, then we'll explain what's happening:

<?PHP
$file_handle = fopen("dictionary.txt", "r");
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
print $line_of_text . "<BR>";
}
fclose($file_handle);
?>

What you should find is that the contents are printed out on separate lines. But how does it work?

The first line is this:

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

What we're doing here is asking PHP to open up a file, and remember the location. The location is stored as a file handle. We're putting this into a variable called $file_handle. So we haven't yet read the contents of the file – we've just asked PHP to remember where it is.
The next line is tricky! It's a while loop:

while ( !feof( $file_handle ) ) {
}

There's really two parts to this. There's the while loop:

while () {
}

And then there's the condition for the while loop:

!feof( $file_handle )

A while loop, remember, just goes round and round until you tell it to stop. It goes round and round while a condition is true. The condition between the round brackets was our strange !feof line.

The function feof( ) means "file end of file". It tells PHP when the end of a file has been reached. You put the file between the round brackets of the function:

feof( $file_handle )

This means, end of the file referred to in the variable called $file_handle. Except, we've used the NOT operator ( ! ):

!feof( $file_handle )

That's because we want to keep looping while the end of the has NOT been reached:

while ( !feof( $file_handle ) ) {
}

This whole line, then, reads: "While the end of the file has NOT been reached, loop round the file pointed to in $file_handle." As soon as the end of the file has been reached, the while loop will end.

Inside the while loop, the first line is this:

$line_of_text = fgets( $file_handle );

We're using the fgets( ) function to get a line of text from our file. Again, we need the file handle:
fgets( $file_handle );

So we get a line of text from our file, and then place the line into a variable. We then print out the line of text:

print $line_of_text . "<BR>";

As well as printing out the line of text, we're adding a HTML line break.

The last line in the code is this:

fclose( $file_handle );

All this does is to close the open file. It tells PHP that the pointer to the file is no longer needed. You should always close files that you have opened with fopen().

The code is a bit tricky, when you're meeting it for the first time. But this kind of file opening is useful when you need to read each line of text. With our file, for example, we could separate each half of the line. We might want to put the abbreviations into one list box and the meanings into another.

Another point to bear in mind about fgets is that it can take (and often does) a second argument – the size of the line to read:

fgets($file_handle, line_size);

The line size needs to be in bytes. The default is 1024. But this line size is only optional in PHP version 4.2 and above. If your version is earlier than this, then you may get an error if you miss out the line size:

fgets($file_handle, 1024);

If you're really packing a lot of information into each line, then just increase the number for line size.

we used fopen and to get at our file. But we were only reading the file. That's was why we had the letter "r" in the round brackets of fopen:

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

But there are other options. Here's a fuller list of things you can replace "r" with.

So if you wanted to read and write to the file, you'd use this:
$file_handle = fopen("dictionary.txt", "r+");

Or this, if you want to append data to the end of file when you're writing it back:
$file_handle = fopen("dictionary.txt", "a+");

If you need to work with binary files (like images), then you can add the "b":
$file_handle = fopen("dictionary.txt", "rb");

Checking if the file exists

It's a good idea to check if the file exists, before trying to do something with it. The file_exists( ) function can be used for this:

if ( file_exists( "dictionary2.txt" ) ) {
print "file exists";
}
else {
print "file doesn't exist";
}

In between the round brackets of file_exists( ) you then type name of your file. If it does exist, then you can go ahead and do something with it; if not, you can write code to handle any errors.

When you need to write to files, there are some more functions you need to use. If you have a version of PHP below version 5, then you can use the fwrite() function. But you first need to usefopen( ) to get a file handle.

In the next script, we'll try to write some text to a file. We'll use the "w" option, as this will create a file for us, if we don't have one with the filename chosen.

<?PHP
$file_handle = fopen("testFile.txt", "w");
$file_contents = "Some test text";
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";
?>

The new line is the blue coloured one. First we ask PHP to open the file and create a file handle:

$file_handle = fopen("testFile.txt", "w");

So we're asking PHP to create a file handle that points to a text file called "testFile.txt". If a file of this name can't be found, then one will be created with this name. After a comma, we've typed "w". This tells PHP that the file will be write only.

The third line is where we write to the file:

fwrite( $file_handle, $file_contents );

In between the round brackets of fwrite( ), we've placed two things: the file we want to write to, and the contents of the file. And, except for closing the file, that's all you need!

To test to see if it works, run the script. Then look in the folder where you saved the script to. There should now be a file called testFile.txt.

Exercise
Change the "w" into "a". Run your script a few times, then open the text file. What did you notice?

Exercise
Change the "a" into "r". Run your script again, then open the text file. What did you notice? Did the contents of the text file change?

file_put_contents( )

If you have PHP 5, you can use the new function file_put_contents( ) instead of fwrite( ).
It is used in the same way, but has an optional third parameter:

file_put_contents($file_handle, $file_contents, context);

The context option can be FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX.
So to append to the file, just do this:

file_put_contents($file_handle, $file_contents, FILE_APPEND);