PHP Basic File Handling Tutorial

In this tutorial we learn how to work with external files such as csv, or txt. We cover how to open, read, write to, close and delete files in PHP.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is file handling?

When developing a web application, we may often need to work with external files such as .txt, .csv etc. PHP provides pre-defined functions for these file handling operations to make it easier and faster to handle files and the data inside them.

The table below shows the functions available for file handling:

FunctionDescription
fopen()Open/Create a file
fread()Read a file
fwrite()Write/Append to a file
fclose()Close a file
unlink()Delete a file

How to create a new file

The fopen() function is responsible for opening a file, but if the file does not exist PHP will create the file for us.

Syntax: create a file with fopen()
 fopen("filename", "mode") or die("File operation unsuccessful");

The fopen() function requires a mode that tells PHP what to do when creating the file. The following table shows the available modes:

ModeDescription
rOpen a file with read only privileges. The pointer starts at the beginning of the file.
wOpen a file with write only privileges. If the file does not exist, create it. If the file exists, erase the contents. The pointer starts at the beginning of the file.
aOpen a file with write only privileges. If the file does not exist, create it. If the file exists, preserve existing data. The pointer starts at the end of the file.
xCreates a new file with write only privileges. If the file exists, return false and raise an error.
r+Open a file with read/write privileges. The pointer starts at the beginning of the file.
w+Open a file with read/write privileges. If the file does not exist, create it. If the file exists, erase the contents. The pointer starts at the beginning of the file.
a+Open a file with read/write privileges. If the file does not exist, create it. If the file exists, preserve existing data. The pointer starts at the end of the file.
x+Creates a new file with read/write privileges. If the file exists, return false and raise an error.

We also tell the interpreter to stop execution if the file operation is unsuccessful with the die() function.

Example: main.php - create a new file with fopen()
<?php

$handle = fopen("file.txt", "w") or die ("File operation unsuccessful");
echo $handle;

?>

When we run the example above, a file calle file.txt is created in our PHPProjects directory.

How to write to a file

Now that the file has been created, we can write data to it with the fwrite() function.

Syntax:
 fwrite(ResourceID, "data to write to the file");

Before writing to a file we must open the file with the appropriate mode for writing privileges. The fopen() function returns the resource id that we need to reference.

Example: main.php - write to a file with fwrite()
<?php

$handle = fopen("file.txt", "a") or die ("File operation unsuccessful");

fwrite($handle, "Best movies of all time:\n");
fwrite($handle, "1. The Godfather\n");
fwrite($handle, "2. Star Wars: Episode V\n");
fwrite($handle, "3. The Dark Knight\n");
fwrite($handle, "4. Pulp Fiction\n");
fwrite($handle, "5. Back To The Future\n");

?>

In the example above, we use the resource id returned from the fopen() function as the file to write to. We also open the file with mode a so that existing data inside the file is preserved and we don’t overwrite anything. Essentially we’re appending to the file.

When we open file.txt, we can see that the list of movies has been written to it successfully.

In a real world situation it’s more likely that the data will be in an array, in which case we can use a loop to write the data to the file.

Example: main.php - write to a file with a loop
<?php

$list = array("6. Alien\n", "7. Fight Club\n", "8. Die Hard\n", "9. Jurassic Park\n", "10. Inception\n");

$handle = fopen("file.txt", "a") or die ("File operation unsuccessful");

foreach($list as $item) {
    fwrite($handle, $item);
}

?>

When we run the example above, it will add all the items in the array to our file.txt which we can confirm by opening the file.

Output:
Best movies of all time:
1. The Godfather
2. Star Wars: Episode V
3. The Dark Knight
4. Pulp Fiction
5. Back To The Future
6. Alien
7. Fight Club
8. Die Hard
9. Jurassic Park
10. Inception

How to read from a file

PHP provides us with two main options to read a file:

  • readfile(): reads the entire file.
  • fread(): reads only a specific amount of bytes.
Read a file with readfile()

When we just want to read the whole file into the output buffer, we use the readfile() function.

In this case we don’t need to open the file beforehand because the readfile() function will do it for us.

Syntax:
 readfile("filename");

The readfile() function only outputs the file to the output buffer. If we want to see it on the webpage, we will need to print it.

Example: main.php - read from a file with readfile()
<?php

echo readfile("file.txt");

?>

When we run the example above, we can see that everything inside file.txt is printed to the browser.

You may have noticed though that everything is on one line instead of multiple lines, as we defined in the file.

PHP preserves the linebreaks (\n) in the output, but in HTML the whitespace is collapsed by default. If we want to preserve it, we can use the whitespace CSS attribute.

Example: main.php - preserve readfile() linebreaks
<div style="white-space: pre">
    <?php echo readfile('file.txt'); ?>
</div>

When we run the example above, the linebreaks will be respected and the output will look similar to the actual text file.

Read a file with fread()

We can use the fread() function to read the entire file or just a specific amount of bytes.

The fread() function needs a resource id as its first parameter so we need to open the file beforehand.

Syntax:
 fread(ResourceID, bytes_to_read);

If the file is a document that contains text, 1 byte is equivalent to 1 character.

Example: main.php - read bytes from a file with fread()
<?php

$handle = fopen("file.txt", "r") or die ("File operation unsuccessful");

echo fread($handle, 23);

?>

When we run the example above, it prints out the first 23 bytes (Best movies of all time) to the page.

To read the whole file with the fread() function, we need to calculate its size and use that size for the length parameter.

PHP provides us with the filesize() function to calculate the size of a file.

Syntax:
 fread(ResourceID, filesize("filename"));
Example: read the whole file with fread()
<div style="white-space: pre">
<?php

$handle = fopen("file.txt", "r") or die ("File operation unsuccessful");

echo fread($handle, filesize("file.txt"));

?>
</div>

In the example above, we again wrap the output in a div that preserves the linebreaks.

Read a file line by line with fgets()

PHP provides us with the fgets() function to read the contents of a file until it reaches the newline character (\n).

The fgets() function needs a resource id so the file must be opened beforehand.

Syntax:
 fgets(ResourceID);
Example: main.php - read the file line by line
<?php

$handle = fopen("file.txt", "r") or die ("File operation unsuccessful");

// Read the first line
echo fgets($handle) . "<br>";
// Read the second line
echo fgets($handle);

?>

When we run the example above it will print out the first two lines of file.txt.

We can also read the whole file this way within a loop by evaluating if the pointer is at the end of the file. The feof() function can be used to return true if the pointer is at the end of the file.

Example: main.php loop through file line by line with feof() and fgets()
<?php

$handle = fopen("file.txt", "r") or die ("File operation unsuccessful");

while(!feof($handle)) {
    echo fgets($handle) . "<br>";
}

?>

How to close a file with fclose()

It’s good practice to close a file after using it so that the resources connected to it can be released. In PHP the fclose() function is used to close files.

Syntax:
 fclose(ResourceID);
Example:
<?php

$handle = fopen("file.txt", "r") or die ("File operation unsuccessful");

while(!feof($handle)) {
    echo fgets($handle) . "<br>";
}

fclose($handle);

// Will raise an exception if we try to
// access the file after it's closed
echo fgets($handle);

?>

When we run the example above, the file is closed after the contents of the file is printed to the screen. When we try to access the first line of the file again an error is raised because the file is no longer open.

Output:
 Warning: fgets(): supplied resource is not a valid stream resource on line 12

In many cases files will only be stored on the server for a limited time like file converter applications or cloud storage. When a file needs to be deleted we can use the unlink() function.

Syntax:
 unlink("filename");
Example: main.php - unlink() a file to delete it
<?php

if(unlink("file.txt")) {
    echo "file.txt has been deleted successfully";
}

?>

Summary: Points to remember

  • The fopen() function can both open and create files.
  • The readfile() function automatically opens the file before reading it, so we don’t have to.
  • It’s always good practice to close the file when we’re done working with it.