File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or handling uploads.
Table of Content
In this article, you will learn everything you need to know about file handling in PHP. Let’s get started.
File handling means working with files on your server. PHP provides several built-in functions to open, read, write, and delete files. These functions let you handle files efficiently while keeping things easy to manage.
Here are some of the built-in functions for file handling in PHP:
- fopen(): Opens a file.
- fclose(): Closes a file.
- fread(): Reads data from a file.
- fwrite(): Writes data to a file.
- file_exists(): Checks if a file exists.
unlink(): Deletes a file.
You need to specify a mode when opening a file. These modes tell PHP how you intend to work with the file. Here are some modes:
- ‘r’: Read-only. The file must exist.\n
- ‘w’: Write-only. Creates a new file or overwrites an existing file.
- ‘a’: Append. Adds data to the end of the file without overwriting.
- ‘x’: Exclusive create. Fails if the file already exists.
- ‘r+’: Read and write.
Each mode serves a specific purpose, so pick one based on what you need to do.
In the following section, you will learn how to read files in PHP.
Reading Files in PHP
PHP provides multiple ways to read files. We just need to use each method to read the flatcoding.txt file.
Here is how you can do it:
Read Files with fread()
Here is an example:
// flatcoding.txt => contains this text (Hello, this is the content of flatcoding.txt)
$file = fopen("flatcoding.txt", "r");
if ($file) {
$content = fread($file, filesize("flatcoding.txt"));
fclose($file);
echo $content;
} else {
echo "Failed to open the file.";
}
The output of this example would be like below:
Hello, this is the content of flatcoding.txt
This reads the contents of a file named flatcoding.txt and prints it to the screen. It first tries to open the file in “read” mode using fopen. If the file is successfully opened, it reads the entire content using fread, closes the file with fclose, and displays the content using echo. If something goes wrong (like the file does not exist or there is a permissions issue), It handles the error by printing “Failed to open the file.”.
There is another way to read files, which is the built-in function in PHP, file_get_contents. Let’s move on to the following section to see how it works.
Read File with file_get_contents()
Here is an example:
$content = file_get_contents("example.txt");
if ($content !== false) {
echo $content;
} else {
echo "Failed to read the file.";
}
We used the file_get_contents to read the file “flatcoding.txt”. If the operation is successful, it stores the file’s content in the $content variable and prints it using echo. On the other hand, if something goes wrong (like the file does not exist or there is an issue reading it), the if statement detects this and outputs “Failed to read the file.”.
So, how do you write to the file you already opened in the previous PHP example? Let’s move into that in the following section.
Writing Files in PHP
There are two ways to do this task. Let’s take a look at each one with an example.
Write Fiels with fwrite() Function
Here is an example:
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "This is a new line of text.");
fclose($file);
echo "File written successfully.";
} else {
echo "Failed to write to the file.";
}
The fwrite function writes the text "This is a new line of text." into the file. After writing, the file is closed with fclose to ensure changes are saved properly. It prints “File written successfully.” If there is an issue opening the file (like permission problems), it will instead print “Failed to write to the file.”.
Let’s do the same task with file_put_contents().
Writing Files by file_put_contents()
Here is an example:
$result = file_put_contents("example.txt", "Overwritten content.");
if ($result !== false) {
echo "File written successfully.";
} else {
echo "Failed to write to the file.";
}
Here, I used the file_put_contents function to write the string "Overwritten content." to the file example.txt. It will create a new one If the file does not exist
In the following section, you will learn how to append data into files in PHP.
Append Data to Existing Data
To add data to a file without overwriting the existing content, you can open the file in “append” mode using the "a" flag. This ensures that new content is added to the end of the file. Here is an example:
$file = fopen("example.txt", "a");
if ($file) {
fwrite($file, "This is an appended line of text.\n");
fclose($file);
echo "Data appended successfully.";
} else {
echo "Failed to append to the file.";
}
The “a” flag opens the file in append mode. If the file does not exist, it creates a new one. fwrite adds the specified text to the end of the file, without removing the existing content. \n adds a new line after the appended text, ensuring the next addition starts on a new line. It prints “Failed to append to the file.” If the file cannot be opened.
You can do the same job with file_put_contents(). Here is an example:
$result = file_put_contents("example.txt", "\nAnother line.", FILE_APPEND);
if ($result !== false) {
echo "Data appended successfully.";
} else {
echo "Failed to append to the file.";
}
Both will append text to the end of the file.
In the following section, you will learn how to check if the current file already exists on the drive in PHP.
Checking If a File Exists
It is always good to check if the file exists before performing file operations. Here is an example:
if (file_exists("example.txt")) {
echo "The file exists.";
} else {
echo "The file does not exist.";
}
This will check if the file exists in the directory. If it does, it will print “The file exists.” Otherwise, it will print “The file does not exist.”.
Let’s move on to the following section to learn how to delete a file in a specific path using PHP.
Deleting Files
You can use the unlink() function to delete a file in a specific directory. Here is an example:
if (file_exists("example.txt")) {
if (unlink("example.txt")) {
echo "File deleted successfully.";
} else {
echo "Failed to delete the file.";
}
} else {
echo "File does not exist.";
}
The file_exists function helps us detect the existence of a file. If it already exists, it will delete the file from the directory.
Let’s summarize.
Wrapping Up
File handling in PHP helps you to read, write, append data, or deleting files. Here are a quick recap:
- File operations with
fopen(),fclose(),fread(), andfwrite()for basic file handling tasks. - Checking files using file_exists() function ensures the file’s existence before performing operations.
- Appending data by using the “a” mode or
FILE_APPENDwithfile_put_contents()to add content without overwriting. - Deleting files with
unlink()function to remove files. - Reading by using
file_get_contents()for file reading.
Similar Reads
Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand…
The PHP logical operators are operands that can be used to check two or more expressions together. For examples (…
Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…
When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…
PHP developers may be need to determine the number of elements in an array. The count() function in PHP makes…
pplications. Such As as From registering new users to collecting form submissions and storing product details. Things like adding a…
Type casting in PHP refers to the process of converting a variable from one data type to another. This is…
In regard to the use of constants in PHP, clear understanding of their definition and use could be critical in…
The OOP constructor initializes an object when it is created in PHP. Understand What a Constructor Is in PHP A…
PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…