- PHP File Open/Read/Close
- PHP Open File — fopen()
- Example
- PHP Read File — fread()
- PHP Close File — fclose()
- PHP Read Single Line — fgets()
- Example
- PHP Check End-Of-File — feof()
- Example
- PHP Read Single Character — fgetc()
- Example
- Complete PHP Filesystem Reference
- Write to Files and Read Files With PHP
- Checking if a File Exists
- Making Sure That the File Actually Exists
- Reading Data From a File in PHP
- The file_get_contents() Function
- Writing Data to a File in PHP
- The file_put_contents Function
- Examples of Reading and Writing Data
- The file_get_contents Function
PHP File Open/Read/Close
In this chapter we will teach you how to open, read, and close a file on the server.
PHP Open File — fopen()
A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.
We will use the text file, «webdictionary.txt», during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
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
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fread($myfile,filesize(«webdictionary.txt»));
fclose($myfile);
?>?php
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open 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 |
a | Open 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 |
x | Creates 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 |
PHP Read File — fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the «webdictionary.txt» file to the end:
PHP 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 Read Single Line — fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the «webdictionary.txt» file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fgets($myfile);
fclose($myfile);
?>?php
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP 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 «webdictionary.txt» file line by line, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one line until end-of-file
while(!feof($myfile)) echo fgets($myfile) . «
«;
>
fclose($myfile);
?>?php
PHP Read Single Character — fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the «webdictionary.txt» file character by character, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one character until end-of-file
while(!feof($myfile)) echo fgetc($myfile);
>
fclose($myfile);
?>?php
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
Write to Files and Read Files With PHP
Monty Shokeen Last updated May 7, 2022
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: