File Handling in PHP
File Handling in PHP
File handling in PHP allows you to create, read, write, and manage files on the server. It is useful for storing data, logging information, and processing files in web applications.
What is File Handling
File handling refers to performing operations on files such as opening, reading, writing, and closing them using PHP functions.
Opening a File in PHP
To work with a file, you first need to open it using the fopen() function.
$file = fopen(“test.txt”, “r”);
?>
File Modes
"r"– Read only"w"– Write only (creates new file or overwrites)"a"– Append data"r+"– Read and write
Reading a File
You can read file content using functions like fread() or fgets().
$file = fopen(“test.txt”, “r”);
echo fread($file, filesize(“test.txt”));
fclose($file);
?>
Writing to a File
You can write data into a file using fwrite().
$file = fopen(“test.txt”, “w”);
fwrite($file, “Hello PHP File Handling”);
fclose($file);
?>
Appending Data to a File
To add content without deleting existing data, use append mode.
$file = fopen(“test.txt”, “a”);
fwrite($file, ” New content added”);
fclose($file);
?>
Closing a File
Always close the file after operations using fclose() to free resources.
Checking if File Exists
if (file_exists(“test.txt”)) {
echo “File exists”;
}
?>
Why File Handling is Important
File handling is used for storing logs, managing uploaded files, saving user data, and handling reports. It is widely used in real-world applications.
Best Practices
Always Close Files
Use fclose() after file operations.
Handle Errors
Check if the file exists before reading.
Use Proper File Modes
Choose the correct mode to avoid data loss.
Start Your Learning Journey
Want to explore more courses like this? click here for free courses
FAQs – File Handling in PHP
What is file handling in PHP
It is the process of reading, writing, and managing files using PHP.
What does fopen do
It opens a file for reading or writing.
How do you write to a file in PHP
Using the fwrite() function.
What is append mode
It adds data to the end of a file without deleting existing content.
Why close a file in PHP
To free system resources and avoid errors.



