Reading from and Writing to Files in PHP

Files are stored in directories on a hard drive, and because they retain their data after the computer is shut down, they are a persistent storage mechanism, instead of temporary storage such as RAM.

As a server-side programming language, PHP allows you to work with files and directories stored on the Web server. This is very useful, because it means your PHP scripts can store information outside the scripts themselves.

Files

Everything on your hard drive is stored as a file of one kind or another. A file is nothing more than an ordered sequence of bytes stored on a hard disk or other storage media.

A directory is a special type of file that holds the names of the files and directories inside the folder (sometimes denoted as subdirectories or subfolders ) and pointers to their storage areas on the media.


Open File - fopen()

Files are opened in PHP using the fopen() command. The command takes two parameters, the file to be opened, and the mode in which to open the file.

The function returns a file pointer if successful, otherwise zero (false). Files are opened with fopen() for reading or writing.

The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened.

The following example also generates a message if the fopen() function is unable to open the specified file.

Example:

<?php
	if (!($myfile = fopen("myfile.txt", "r")))
	exit("Unable to open the input file.");
?>

File Modes

The following table shows the different modes the file may be opened in.

ModesDescription
rOpen a file for read only. File pointer starts at the beginning of the file
wOpen a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
aOpen a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
xCreates a new file for write only. Returns FALSE and an error if file already exists
r+Open a file for read/write. File pointer starts at the beginning of the file
w+Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+Creates a new file for read/write. Returns FALSE and an error if file already exists

Reading from Files - Using fread()

Now that you know how to open and close files, it's time to take a look at reading and writing data in a file.

The fread() function can be used to read a string of characters from a file. It takes two arguments: a file handle and the number of characters to read.

The function reads the specified number of characters (or less if the end of the file is reached) and returns them as a string.

Example:

$handle = fopen("myfile.txt", "r");
$data = fread($handle, 10);

This code reads the first ten characters from myfile.txt and assigns them to $data as a string.

After fread() has finished, the file pointer, which holds the current position in the file, moves forward in the file by the number of characters read.

So after the previous example code runs, the file pointer moves forward to ten characters after the start of the file.

If you repeat the same call to fread() , you'll get the next ten characters in the file. If there are less than ten characters left to read in the file, fread() simply reads and returns as many as there are.


Reading from Files - Using fgetc()

If you want to read only one character at a time you can use the fgetc() function.

fgetc() takes a single argument a file handle and returns just one character from the file it points to it returns false when it reaches the end of the file.

Example:

<?php
	$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
	echo fgetc($myfile);
	fclose($myfile);
?>

However, fgetc() is slow when working with large files. It is faster to read a bunch of characters at once using fread(), or one of the other file.

Note: After a call to the fgetc() function, the file pointer has moved to the next line.


Check End-Of-File - feof()

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "myfile.txt" file line by line, until end-of-line is reached.

<?php
	$myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
	// Output one line until end-of-file
	while(!feof($myfile)) {
 		echo fgetc($myfile) . "<br>";
	}
	fclose($myfile);
?>

Close File - fclose()

The fclose() function is used to close an open file.

It's a good programming practice to close all files after you have finished with them. You don't want an open file running around on your server taking up resources.

The fclose() requires the name of the file (or a variable that holds the filename) we want to close.

<?php
	$myfile = fopen("myfile.txt", "r");
	// some code to be executed....
	fclose($myfile);
?>

PHP Write to File - fwrite()

The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

The example below writes a couple of names into a new file called “newfile.txt”.

Example:

<?php
	$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
	$txt = "John Doe\n";
	fwrite($myfile, $txt);
	$txt = "Jane Doe\n";
	fwrite($myfile, $txt);
	fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first contained "John Doe" and second contained "Jane Doe".

After we finished writing, we closed the file using the fclose() function. If we open the "newfile.txt" file it would look like this.

John Doe 
Jane Doe

PHP File Formats Support

PHP file functions support a wide range of file formats that include;

  • File.txt
  • File.log
  • File.custom_extension i.e. file.xyz
  • File.csv
  • File.gif, file.jpg etc
  • Files provide a permanent cost effective data storage solution for simple data compared to databases that require other software and skills to manage DBMS systems.
  • You want to store simple data such as server logs for later retrieval and analysis
  • You want to store program settings i.e. program.ini