Ken Ward's PHP Tutorial

Files

Unlike javascript, php can open files for reading and writing and save files. You can open a file in a particular mode, and then write to it, either overwriting the original contents or appending the new information. To do this, you need to set the Server Permissions to allow these operations. Assuming these are set, you can open and save files with php. The topics on this page are:
  1. How to open a file and read its contents with fopen and fread
  2. How to open a file and append data using fwrite
  3. How to read file data into an array using file()
  4. Writing to a new file (fwrite)
  5. Reading and writing with fputs() and fgets()

How to open a file and read its contents (fopen)

//first we tell php the filename

$file = 'fileDataEx.txt';

// then we try to open the file, using the r mode, for reading only

$fp = fopen($file, 'r') or die('Couldn\'t open file!');

// read file contents

$data = fread($fp, filesize($file)) or die('Couldn\'t read file!');

// close file

fclose($fp);

// print file contents

print "The data in the file is \"".$data."\"";

//The data in the file is "This is line one. This is line two. This is line three."

First we tell php what file we want to open. Then we allocate a file handle to the file (fp). We then open the file for reading using the r mode, for reading only. We put the file data (a string) into a variable ($data) and finally print out the contents of the file.

There are a number of modes for files, but three of them are:

Mode Action
r Open a file for reading only.
w Open a file for writing (originally data is overwritten). If the file doesn't exist, attempt to create it.
a Open a file and append new information, keeping the original data inthe file. If the file doesn't exist, attempt to create it.

 

How to open a file and append data fwrite

When we wish to append data to a file, you first open it with fopen with the "a" mode. You can then write to the file using fwrite.

$filename = 'fileDataEx.txt';

$addcontent = "This is line 4\n"; //this is the content to append to the file

// Try to open the file

$handle = fopen($filename, 'a') or die ("Can't open file ($filename)");

// Try to write to open file

fwrite($handle, $addcontent) or die ("Can't write to file ($filename)");

So far, we have named the file, fileDataEx.txt, and defined a variable with the data we wish to add to the file ($addcontent). We try to open the file with fopen in append mode (a). The "or die" statement is the equivalent of exit, with a message. It tells us where the problem occurred. Finally, we use fwrite to try to write to the file.

So we have appended the text to the file. The rest of the code is just checking that we have actually written the text. We try to open the file for reading, using the "r" mode, and then read the file with fread.

The echo "Success..." will not print if any errors occur in opening and writing to the file. Reasons for failure may mean that certain permissions have not been set on the server.

$handle = fopen($filename, 'r') or die('Couldn\'t open file!');

$data = fread($handle, filesize($filename)) or die ('Couldn\'t read file!');

echo "Success, wrote ($somecontent) to file ($filename)";

echo "The new file now is: ".$data;

fclose($handle);

//Success, wrote () to file (fileDataEx.txt)The new file now is: This is line one. This is line two. This is line three.

Reading a file into an array using file()

Using file is far easier than using fopen and fread. You save lines of code by not having to open the file and close it. Also the code is easier. Also file() works when fread doesn't! So this lazy way is also a far better way.

$file = 'fileDataEx.txt';

// read file into array

$data = file($file) or die('Could not read file!');

// show the new contents of the file

foreach ($data as $line) {

echo $line."<br>";

}

/*This is line one.

This is line two.

This is line three.

This is line 4 */

Most of the code above is about printing the file. Having got the data into the array $data, we need only go through the array and print each line.

Writing to a new file

To write to a new file, you can open the file in "w" mode and use fwrite(). The following example shows how. However, depending on the setting on the server, the file create may fail, as it did in this case:

$filename = 'fileDataEx2.txt';

// open file

$header = fopen($filename, 'w') or die('Could not open file!');

// write to file

$data="dog

cat

mouse";

fwrite($header, $data) or die('Could not write to file');

// close file

fclose($header);

//Warning: fopen("fileDataEx2.php", "w") - Permission denied on line 55

//Could not open file!

After creating the file and setting the file permissions, I succeeded in writing to the file.

Having written to the file, I read it as follows:

$filename = 'fileDataEx2.txt';

$data = file($filename) or die('Could not read file!');

foreach ($data as $line) { echo $line."<br>"; }

/*dog

cat

mouse*/

This is similar to the previous example with file(). Because the stuff written to the file was separated by line breaks in the string, this data was written to the file in lines, and retrieved by file() into an array as separate values. This is shown by the print which separates the values in different lines.

Reading and writing to files using fputs and fgets

Here is an example of fgets (file get string (line)):

//fgets

$handle = fopen("fileDataEx.txt", "r"); //open file for reading

echo "Using fgets<br>";

//Using fgets

while (!feof($handle)) { //while not end of file

$buffer = fgets($handle, 4096); //use fgets with file handle, specifying size

/*4096 is just the size of the longest line likely, and fgets stops at the end of the line or 4096. Without some size here, fgets might stop at a zero byte in the line rather than the end of the line*/

echo $buffer; //print out the line

}

fclose($handle); //close the file

// File Contents: This is line one. This is line two. This is line three. This is line 4 This is line 4 This is line 4

fputs is the same as fwrite.

//fputs

$handle = fopen("fileDataEx2.txt", "a") or die ("Couldn't open the file"); //open file for reading

//make a string
$string="apples

pears

oranges ";

//Using fputs
fputs($handle,$string,strlen($string)) or die("Couldn't append to the file");
fclose($handle); //close the file

In the above example, we used strlen to find the length of the string to write to the file instead of using 4096, for the longest string expected.

We write the file out again to see if fputs worked:

//read file
$handle = fopen("fileDataEx2.txt", "r") or die ("Couldn't open the file"); //open file for reading

//Using fgets to read file
while (!feof($handle)) { //while not end of file
$buffer = $buffer.fgets($handle, 4096) or die("Couldn't read the file"); //use fgets with file handle, specifying size
}

echo "\$buffer is $buffer"; //print out the file we have appended to
//$buffer is Previous stuff in file apples pears oranges

We note that the stuff we appended with fputs is added to the file contents (Previously, the file read: "Previous stuff in file").

Reference

PHP Manual

Further information from the php manual.