How to create write read and delete files in php

Updated: 25-Aug-2022 / Tags: PHP Lang Reference / Views: 756

Introduction

Hey guys.

As a php programmer you will use very often the php built-in filesystem functions to create, read, write, and delete files.

So in this tutorial we are going to see in detail how we can use those functions to do this.

Let's see the functions that we are going to work with.

  • touch() ... to create a file.
  • file_put_contents() ... create and write in a file at the same time.
  • fopen() and fwrite() ... create and write in a file at the same time.
  • fopen() and fread() ... read from a file.
  • file_get_contents() ... read from a file.
  • unlink() ... delete a file from the filesystem.

Now, let's start creating files.

Creating a file

The touch function

The first function that we are gonna use to create a file is the touch() function.

The touch() function actually modifies the accessed timestamp of the file and sets it to the current system time. In plain English, every time we "touch" a file, we modify the last accessed timestamp to the current time. But if the file doesn't exist it will be created.

touch("Documents/new-file.txt");
  • In our case we are creating a file named new-file.txt inside the Documents/ folder.
  • The touch() function returns true on success, or false when it fails.
    Knowing this we can wrap the touch() function in an if statement, so that we know if the function created the file or not.

    if (touch("Documents/new-file.txt") == false) {
    	// display error message
    }else{
    	// do something with the file
    }
    		

    This is how we use the touch() function, now let's see the next one.

The file_put_contents function

With the file_put_contents() function we can create a file and write to it in the same time.
Let's see how we use the function.

file_put_contents("Documents/new-file.txt", "Some data to write in a file");
  • The file_put_contents() function writes data to a file. The function takes two arguments. In the first argument we have the file's path, and in the second argument we have the data that we are writing to the file.

    If the file doesn't exist it will be created. But if the file exists it will be overridden. This means that any stored data are going to be erased. We will see how to avoid this, a few lines down.

  • The function returns the number of bytes written on the file, or false on failure.
    Lets see this.
    echo file_put_contents("new-file.txt", "Some data to write in a file"); 
    // outputs 29 
  • If we open in the editor the new-file.txt file we will see our data in the file:
    Some data to write in a file
    
  • If we run the function again, and write a different string of data in the file...

    file_put_contents("new-file.txt", "Another string of data");

    ... we will see this:

    Another string of data
    
    We see that the previous data where erased.
  • If we want to append data to the file we have to use the FILE_APPEND flag.

    file_put_contents("new-file.txt", "A second string of data", FILE_APPEND);

    Now we see this:

    Another string of data A second string of data
    

    We see both entries in the same line. This is not what we want. To insert the data that we append, to a new line, we have to use the "\n" (end of line character) at the end of our string if we are on a unix system, or \r\n if we are on windows. Lets run the function three times and try it out.

    file_put_contents("new-file.txt", "A string of data \r\n", FILE_APPEND);
    file_put_contents("new-file.txt", "A second string of data \r\n", FILE_APPEND);
    file_put_contents("new-file.txt", "A third string of data \r\n", FILE_APPEND);
    		

    Now we will see every record in different line:
    A string of data 
    A second string of data
    A third string of data 
    

    The end of line characters "\r\n" are invisible.

    This is how we create and write data to a file in the same time using the file_put_contents() function. Now lets move to the next function which is the fopen() and fwrite().

The fwrite function

The fwrite() function doesn't go alone. We have a set o functions to create and write to a file.

$handler = fopen("new-file.txt", "w"); 
fwrite($handler, "A string of data \r\n");
fclose($handler);
  • First of all we have to use the fopen() function to open an existing file. If the file doesn't exists, it will be created. We saw the same thing with the file_put_contents() function.

    The fopen() function takes two parameters. In the first parameter we have the file we want to write or create, and in the second parameter we are setting the file's mode. In this case with the "w" we are setting the file's mode to write. Later on we will see other modes like "a" (append), and "r" (read).

    The function returns a file pointer resource on success, or false on failure.

    The file pointer resource contains information about the file such as the file state, indicators, pointers, and represents a file stream.

    Now we are taking the returned file stream and assign it to the $handler variable so we can operate upon the file.

  • In line 2 we have the fwrite() function.

    fwrite($handler, "A string of data");

    The fwrite() function takes two arguments. The first argument is the file stream that the fopen() function returned. And in the second argument we have the data that we want to record.

    The function returns the number of bytes that are recorded to the file, or false on failure.

  • In line 3 we have the fclose() function. The fclose() function takes one argument and that is the file stream.

    fclose($handler);

    The fclose() function closes the file stream and clears the allocated space from the memory.

  • If we run this code block the data in the file will be replaced with the new one, because we set the mode to "w" (write) in the fopen() function.

    If we want to append data we have to use the "a" mode with the fopen() function.
    Let's see how we do this.

Append data with the fwrite function

The only thing that we have to change to append data to our file is to set the second argument of the fopen() function to the "a" (append) mode.

$handler = fopen("new-file.txt", "a"); // Using the "a" mode.
fwrite($handler, "A string of data \r\n"); // "\r\n" create a new line.
fclose($handler);
  • Also you see we added at the end of the string, the end of line characters "\r\n", so every record will be added in a different line.

    Now let's see how we read files

Reading a file

In this section we are going to read the data below that we inserted in the new-file.txt file.

A string of data 
A second string of data 
A third string of data 

The file_get_contents function

With the file_get_contents() function we can read the files content. The function returns the file's content as a string or false on failure. The function takes as an argument the file's filepath.

$file = file_get_contents("new-file.txt");

If we echo the $file variable...

echo $file;

... we will get something like this:

A string of dataA second string of dataA third string of data

You see that although our records in the file are in different lines, the file_get_contents() function reads everything as a string. Now there is a function that can help us to catch the data as they are in the file, and that is the nl2br() function.

echo nl2br($file);

The nl2br() function inserts line breaks before all new lines in a string. Now our output looks like this:

A string of data 
A second string of data 
A third string of data 

Now let's see how to read the file with the fread() function.

The fread function

Now we are going to use the fopen() and the fread() functions to read the data from the new-file.txt file.

$handler = fopen("new-file.txt", "r"); 
$file = fread($handler, filesize("new-file.txt"));
fclose($handler);

echo nl2br($file);
  • In line 1 we use again the fopen() function to open the file stream and store it in the $handler variable. The difference this time is in the mode. We set the mode to read only "r".
  • In line 2 we have the fread() function. The fread() function returns the file's content as a string or false on failure.

    The function takes two arguments. The first argument is the file stream, and the second argument is the length of the data that we want to read.

    Since we want to read all the file and we don't know the number of bytes (size), we use the filesize() function which returns the size of the file in bytes. In this way we read all the data from the file.

  • In line 3 we close the file stream.
  • And in line 5 we use again the nl2br() function to add line breaks to every new line.
    And we get the same result as we did with the file_get_contents() function.

    A string of data 
    A second string of data 
    A third string of data 
    

    Now let's see how to delete a file from the filesystem.

Delete a file

To delete a file we are going to use the unlink() function.

The unlink function

The unlink() function takes as an argument the path of the file that we want to delete.

unlink("new-file.txt");
  • The function returns true on success, or false on failure.

We can also wrap the unlink() function in an if statement.

if(unlink("new-file.txt") == false){
	// echo error deleting file ...
}else{
	// file deleted ....
}

Please be careful with the unlink() function, you can delete valuable data in a blink of an eye if you are not careful enough.

Summary

We saw how to read, write, create, and delete files, using php's built in functions.

Last words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal