# Write to Files and Read Files With PHP

In this tutorial, you'll learn several important functions in PHP which are sufficient for all your basic file reading and writing needs. You'll learn how to read a file, write to a file, write to a text file, and check if a file exists.

File handling is something that you will need to do very often as a PHP developer.

You could use PHP file handling functions to manipulate files in different ways. These functions could be used to build features in your applications that range from custom error logging to storing cached files. Examples of utility tools that you could build with these functions are:

• custom logging and debugging tools
• application configuration storage
• front-end and application caching
• localization support
• and many more

Luckily, PHP provides a lot of functions to read and write data to files. In this tutorial, I'll show you the easiest ways to read data from a local or remote file and how to use flags to write to files exactly how we want.

Section Key Functions
Checking if a File Exists file_exists(), is_file()
Reading Data From a File in PHP file_get_contents()
Writing Data to a File in PHP file_put_contents()
Examples of Reading and Writing Data file_get_contents(), file_put_contents()
Reading and Writing to Files With Streams fopen(), fread(), fwrite()

## Checking if a File Exists

Your very first step when trying to read data from a file or writing something to it should be to check if the file already exists. Trying to read data from a file which does not exist will result in a warning from PHP and will probably crash your code.

The easiest way to check if a file exists is to use the PHP file_exists($filename) function. It will return true if a file or directory with the given $filename exists and false otherwise. This might be obvious, but I would like to point out that $filename doesn't have to just be the name of a file. It can also be an absolute or relative path. For example, we could use prime_numbers.txt or science/project/periodic_table.txt. It's also important to remember that this function will also return false for files which are inaccessible due to safe mode restrictions. Another function that you can use to check for the existence of a file is is_file(). In contrast to file_exists(), this function will only return true if the specified path points to a file and not a directory. ### Making Sure That the File Actually Exists If the code you are writing performs a lot of file operations on a particular file, you might get incorrect results using the above functions. This is because the results of the execution of both file_exists() and is_file() are cached in order to improve performance. PHP also caches the values returned by other filesystem functions like filesize(), filemtime(), etc. You can call clearstatcache() to make sure that any information you are accessing for a file is up to date. This is generally only a problem if the same file is being accessed multiple times in a single script to know its status. Also, the cached data is cleared if you delete the file inside the script using the unlink() function. This basically means that you probably won't face any caching-related problems, but it is still good to know that you can clear the cache in case the information goes stale or if you are getting unexpected results when trying to access information about a file. ## Reading Data From a File in PHP ### The file_get_contents() Function One of the easiest ways to read data from a file in PHP is with the help of the file_get_contents($filename, $use_include_path,$context, $offset,$maxlen) function. It will simply read the entire file and give it to you in the form of a string. All the parameters except the first one are optional.

The second parameter accepts a boolean value to determine if it should look for a file in the location specified by the include path, which can be set using the set_include_path() function.

You can use the third parameter to specify a bunch of options to refine how the files are accessed. You can use it to specify header values like the Cookies and Host, as well as the HTTP method.

The $offset parameter determines the point where reading starts on the original file. Providing a negative value will start counting from the end. The support for negative offsets was only added in PHP 7.1.0. It is worth noting that offset only works with local files and is not supported for remote files. The file_get_contents() function reads the whole file at once by default. You can change this behavior by providing a value for the $maxlen parameter. The length of characters to be read is counted from the offset value.

The file_get_contents() function reads the whole file at once by default. You can change this behavior by providing a value for the $maxlen parameter. The length of characters to be read is counted from the offset value. You can use this function to open remote files, but that would be possible only if the value of the allow-url-fopen option in php.ini is true or 1. ## Writing Data to a File in PHP ### The file_put_contents Function One of the easiest ways to write data to a file in PHP is with the help of the file_put_contents($filename, $data,$flags, $context) function. The $filename parameter determines the file in which the data will be written. The second parameter is the data that you want to write to the file. Most of the time it will be a string, but it could also be an array or a stream resource.

Remember that PHP will automatically create a file with the given name for you if it doesn't already exist. However, it won't create any directories for you. This means that you can store a file with the name On the Origin of Species [Charles Darwin].txt without any error. However, setting $filename to Biology/Evolution/On the Origin of Species [Charles Darwin].txt, if Biology/Evolution/ doesn't already exist, will result in an error. The $flags parameter determines how the content will be written to a file. It can have any or all of the following three values:

• FILE_USE_INCLUDE_PATH—This tells PHP to search for the given file name in the include directory.
• FILE_APPEND—This will tell PHP to append the data you passed to the function to the existing data in the file. It could be useful if you are storing data in a file like a log or a personal diary. Recording new data like temperature or events that happened to you today won't overwrite something you recorded yesterday.
• LOCK_EX—This will tell PHP to get a lock on the file before starting to write content into it. It can prevent unexpected things from happening when two different scripts are reading or writing data to the same file. With this particular value, you will get an exclusive lock on the file. You can read more about these locks in the PHP documentation of the flock() function.

This function returns the number of bytes that were written to the file on success and false on failure. However, you must still use the strict equality operator to check if it was successful in writing content to the file. That's because code that writes 0 bytes to the file will still evaluate to false.

## Examples of Reading and Writing Data

In this section, we'll look at a couple of real-world examples to demonstrate how you can read files.

#### The file_get_contents Function

You can head over to the Project Gutenberg website and try to download files using the  file_get_contents() function. Once you have the data in a string, you can also simply store it in a local file using the file_put_contents() function. The following example will make this clear:

You could save webpages or content from websites like Wikipedia in a similar manner. If you need to make sense of the HTML or parse the HTML content that you just saved locally, you can follow a tutorial like Parsing HTML With PHP Using DiDOM, which will assist you in automatically getting links, image files, or any other such information from the webpage.

Let's get back to local files now. Consider a situation where you have a bunch of text files and you want to analyze their content to see things like the most common words in them. This could be achieved easily using a bunch of built-in PHP functions.

We converted all the text to lowercase and made the assumption that every single word breaks at spaces. The text is then converted to an array using explode() to make it easier to analyze individual words. Surprisingly, the word "evolution" is not used even once in the entire book that gave the theory of evolution its origin.

This was just an example of automatically analyzing a large amount of text. You could do something similar with any kind of text stored in a file.

#### Logging Data With FILE_APPEND

One more useful example would be logging information over small periods of time. It could be your exercise routine, weather data, or a bee colony that you are observing. Once you have the data in a string, you can easily store it in a file and append it to existing data using the FILE_APPEND flag with file_put_contents().

Similar code could be used for something like storing Wikipedia's featured article of the day in a file every day or keeping track of news articles and headlines over the course of weeks or months. All you need to do is write code to scrape the data and then store it using something similar to the above code snippet. A tutorial like Parsing HTML With PHP Using DiDOM can help you with the scraping part.

Instead of writing the text in plain format, you could wrap it in some HTML to make it easier to read in browsers. The possibilities are endless.

## Reading and Writing to Files With Streams

PHP has another API for reading and writing files: the fread and fwrite functions.

### The fopen() Function

The fopen function lets you open a file for reading or writing, and even lets you create a new file.

Let’s look at a simple example to understand how it works.

In the above example, the fopen function will check if the /home/tutsplus/files/tmp.txt file exists, and if it exists, it’ll open it for writing. By supplying 'w' in the second argument, we specify that we will be writing to the file. If the file doesn’t exist, it’ll be created right away. It’s important to note here that the /home/tutsplus/files/ directory in the above example must be writable by the web server user for the fopen function to be able to create a file.

The first argument of the fopen function is the filename which you want to open. In the above example, we’ve supplied the /home/tutsplus/files/tmp.txt filename in the first argument. Again, it’s important to note that we’ve supplied an absolute path name.

The second argument is the mode, which specifies the type of access you require to the opened file. The fopen function provides different modes you can choose from. For example:

Mode Meaning File Erased? Cursor Position

no

beginning
r+ reading and writing  no beginning

w

erase the file and open for writing only yes beginning

w+

erase the file and open for reading and writing yes beginning
a writing in append mode no end
a+ reading and writing in append mode no end

In our example, we’ve used the w mode, which deletes the contents of /home/tutsplus/files/tmp.txt and opens it for writing only.

fopen returns a file system pointer, which is used for the other file functions like reading and writing.

#### Opening Remote Files?

The fopen function isn't just for local files. It also supports other protocols and can open files from elsewhere on your network or the web. If you’ve enabled the allow_url_fopen directive in PHP, you could open remote files as well.

It’s really important to note that when you enable the allow_url_fopen directive, you are creating some security risks, since it opens the door for remote file execution and other attacks. So make sure you take extra security measures in your application if you’re going to enable this directive.

### The fread() function

The fread function allows you to read from a file. It's similar to fwrite, but you need to provide the length in bytes you want to read. You also need to first open the file with fopen.

The first argument of the fread function is the file system pointer, so that it knows where to read from. The second argument is the length in bytes you want to read from a file. You need to use the fopen function to get the file system pointer.

#### Example of Using fread

Let’s have a look at the following example to understand how it works.

As we want to read from the /home/tutsplus/files/tmp.txt file, we’ve opened it with the r mode by using the fopen function. The fopen function does two things: it creates a file if it doesn't exist and also opens it for reading or writing.

Next, we’ve used the fread function to read all the contents of the file into the \$content variable. In our case, we want to read all the contents of the /home/tutsplus/files/tmp.txt file, and thus we’ve used the filesize function to measure the size of the file.

### The fwrite Function

The fwrite function allows you to write string contents to the file stream referenced by the file handle.

The first argument of the fwrite function is the file system pointer returned by fopen—this is how fwrite knows where to write into. And the second argument is a string which we want to write into a file.

#### Example of Using fwrite

Let’s go through the following example to understand how fwrite works.

First, we’ve opened the /home/tutsplus/files/tmp.txt file with the a+ mode, which opens it for reading and writing, with the file pointer placed at the end of the file. Thus, our content will be appended to the end of the file, after any other contents. Next, we’ve used the fwrite function to write a string.

As you can see in the above example, you can use the fwrite function multiple times to write a series of strings before you close the file.

Finally, we’ve used the fclose function to close the file. It takes only one argument, the file pointer that you want to close. It’s always a good practice to close files by using the fclose function once you’ve finished with your file operations.

## Final Thoughts

There are many other ways of reading and writing data to files in PHP. However, file_get_contents() and file_put_contents() will address almost all your basic needs without adding unnecessary complication.

The only time you might face a problem with file_get_contents() is when the file you are reading is very large—like 2GB or more in size. This is because file_get_contents() loads the whole file into memory at once, and there is a good chance of running out of memory with such large files. In that case, you will have to rely on functions like fgets() and fread() to read a small part of the file at once.