PHP File System

In this tutorial you will learn how to create, access (or read) and manipulate files using the PHP's file system functions.

Working with Files and Directories in PHP

Since PHP is a server side programming language, it allows you to work with files and directories stored on the web server. In this tutorial you will learn how to create, access, and manipulate files and directory on your web server using the PHP file system functions.

Opening a File with PHP fopen() Function

To work with a file you first need to open the file. The PHP fopen() function is used to open a file. The basic syntax of the fopen() function can be given with:

fopen(filename, mode)

The first parameter passed to fopen() specifies the name of the file you want to open, and the second parameter specifies in which mode the file should be opened. For example:

Example

Download
  • <?php
  • $handle = fopen("data.txt", "r");
  • ?>

The file may be opened in one of the following modes:

Modes What it does
r Opens the file for reading only.
r+ Opens the file for reading and writing.
w Opens the file for writing only and clears the contents of file. If files does not exist then it attempts to create a file.
w+ Opens the file for reading and writing and clears the contents of file. If files does not exist then it attempts to create a file.
a Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If files does not exist then it attempts to create a file.
x Opens the file for writing only. Returns FALSE and an error if file already exists.
x+ Opens the file for reading and writing. Returns FALSE and an error if file already exists.

If fopen() function fails to open a file it returns false and generate an warning message. So you should implement a simple check whether the file exists or not before trying to access it.

Example

Download
  • <?php
  • if(file_exists("data.txt")){
  •     $file = fopen("data.txt", "r");
  • } else{
  •     die("Error: The file you are trying to access doesn't exist.");
  • }
  • ?>
 

Tip:Operations on files and directories are prone to errors. So it's a good practice to implement some form of error checking so that if an error occurs your script will handle the error gracefully. See the tutorial on PHP Error Handling.


Closing a File with PHP fclose() Function

Once you've finished working with a file, it needs to be closed. The fclose() function is used to close the file, like this:

Example

Download
  • <?php
  • $file = "data.txt";
  •     
  • // Open the file for reading
  • $handle = fopen($file, "r") or die("ERROR: Cannot open the file");
  •     
  • // Some code to be executed
  •     
  • // Closing the file handle
  • fclose($handle);
  • ?>
 

Note:Although PHP automatically close all the open file when script terminates, but it's a good practice to close a file after performing all the operations.


Reading from Files Using the PHP fread() Function

Now that you have understood how to open and close files. In the following section you will learn how to read data from a file.

PHP has several functions for reading data from a file. You can read from just one character to the entire file with a single operation.

Reading Strings of Characters Using PHP

The fread() function can be used to read a string of characters from a file. The basic syntax of this function can be given with.

fread(file handle, length in bytes)

The fread() function takes two parameter — A file handle and the number of bytes to read. The following example reads 20 bytes form the "data.txt" file including spaces. The "data.txt" file simply contains a paragraph of text "The quick brown fox jumps over the lazy dog."

Example

Download
  • <?php
  • $file = "data.txt";
  •     
  • // Open the file for reading
  • $handle = fopen($file, "r") or die("ERROR: Cannot open the file");
  •     
  • // Read in the entire file
  • $content = fread($handle,"20");
  •     
  • // Closing the file handle
  • fclose($handle);
  •     
  • // Display the file content 
  • echo $content;
  • ?>

The above example produce the following output.

The quick brown

Reading an Entire File

The fread() function can be used in conjugation with the filesize() function to read the entire file at once. The filesize() function in the example below is used to determine the number of characters that should be read in.

Example

Download
  • <?php
  • $file = "data.txt";
  •     
  • // Open the file for reading
  • $handle = fopen($file, "r") or die("ERROR: Cannot open the file");
  •     
  • // Reading the entire file
  • $content = fread($handle, filesize($file));
  •     
  • // Closing the file handle
  • fclose($handle);
  •     
  • // Display the file content
  • echo $content;
  • ?>

The easiest way to read the whole contents of a file in PHP is with the file_get_contents() function. This function accepts the name and path to a file, and reads the entire file into a string variable without needing to open it. Here's an example:

Example

Download
  • <?php
  • $file = "data.txt";
  •     
  • // Reading the entire file into a string
  • $content = file_get_contents($file) or die("ERROR: Cannot open the file");
  •     
  • // Display the file content 
  • echo $content;
  • ?>

Another method of reading the whole data form a file is the PHP's file() function. It does a similar job to file_get_contents() function, but it returns the file contents as an array of lines, rather than a single string.

To process the file data, you need to iterate over the array using a foreach loop. Here's an example, which reads a file into an array and then displays it using the loop:

Example

Download
  • <?php
  • $file = "data.txt";
  •     
  • // Reading the entire file into an array
  • $arr = file($file) or die("ERROR: Cannot open the file");
  • foreach($arr as $line){
  •     echo $line;
  • }
  • ?>

Writing the Files Using PHP

You can write data to a file or append to an existing file using the PHP fwrite() function. The basic syntax of this function can be given with:

fwrite(file handle, vstring)

The fwrite() function takes two parameter — A file handle and the string of data that is to be written. Here's an example.

Example

Download
  • <?php
  • $file = "note.txt";
  •     
  • // String of data to be written
  • $data = "The quick brown fox jumps over the lazy dog.";
  •     
  • // Open the file for writing
  • $handle = fopen($file, "w") or die("ERROR: Cannot open the file");
  •     
  • // Write data to the file
  • fwrite($handle, $data) or die ("ERROR: Cannot write the file");
  •     
  • // Closing the file handle
  • fclose($handle);
  •     
  • echo "Data written to the file successfully";
  • ?>

An alternative way is using the file_put_contents() function. It is counterpart of file_get_contents() function and provides an easy method of writing the data to a file without needing to open it.

This function accepts the name and path to a file together with the data to be written to the file. Here's an example:

Example

Download
  • <?php
  • $file = "note.txt";
  •     
  • // String of data to be written
  • $data = "The quick brown fox jumps over the lazy dog.";
  •     
  • // Write data to the file
  • file_put_contents($file, $data) or die("ERROR: Cannot write the file");
  •     
  • echo "Data written to the file successfully";
  • ?>

If the file specified in the file_put_contents() already exists, it will overwirte it by default. If you would like to preserve the file's contents you can pass the special FILE_APPEND flag as a third parameter to the file_put_contents() function. I will simply append the new data to the file instead of overwitting it. Here's an example:

Example

Download
  • <?php
  • $file = "note.txt";
  •     
  • // String of data to be written
  • $data = "The quick brown fox jumps over the lazy dog.";
  •     
  • // Write data to the file
  • file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file");
  •     
  • echo "Data written to the file successfully";
  • ?>

PHP Filesystem Functions

The following table provides the overview of some other useful PHP filesystem functions that can be used for reading and writing the files dynamically.

Function Description
fread() Reads a string of characters from a file.
fwrite() Writes a string of characters to a file.
fgetc() Reads a single character at a time.
feof() Checks to see if the end of the file has been reached.
fgets() Reads a single line at a time.
fgetcsv() Reads a line of comma - separated values.
file() Reads an entire file into an array.
file_get_contents() Reads an entire file into a string without needing to open it.
file_put_contents() Writes a whole string to a file without needing to open it.
fpassthru() Displays the contents of an open file.
readfile() Displays the contents of a file without needing to open it.
fseek() Moves the file pointer to a specific location within an open file.
ftell() Returns the position of the file pointer.
rewind() Moves the file pointer to the start of the file.

Please check out the PHP filesystem reference for other useful PHP filesystem functions.

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.