File Handling in PHP – Complete Guide with Examples

Introduction

File handling is an essential part of web development, especially when working with data storage, logs, uploads, or configuration files. In PHP, file handling allows developers to create, read, write, append, and delete files on the server.

Whether you’re building a simple blog, managing user uploads, or storing application logs, understanding file handling in PHP is crucial. PHP provides a rich set of built-in functions that make file operations easy and efficient.

What is File Handling in PHP?

File handling in PHP refers to the process of performing operations on files such as:

  • Creating new files
  • Reading existing files
  • Writing data into files
  • Appending data
  • Deleting files

PHP treats files as streams of data and provides functions to interact with these streams.

For example, PHP can open a file, read its content line by line, or write new content into it using built-in functions like fopen(), fread(), fwrite(), and fclose().

Syntax

1. Opening a File


$file = fopen("filename.txt", "mode");

File Modes:

  • “r” → Read only
  • “w” → Write (overwrites file)
  • “a” → Append
  • “x” → Create new file
  • “r+” → Read & write

2. Reading a File


$content = fread($file, filesize("filename.txt"));

3. Writing to a File


fwrite($file, "Hello World!"

4. Closing a File


fclose($file);

5. Deleting a File


unlink("filename.txt");

Examples:

Example 1: Create and Write File


$file = fopen("example.txt", "w");
fwrite($file, "Welcome to PHP File Handling!");
fclose($file);
echo "File created and written successfully.";

Example 2: Read File


$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
echo $content;
fclose($file);

Example 3: Append Data


$file = fopen("example.txt", "a");
fwrite($file, "\nThis is appended text.");
fclose($file);

Example 4: Read File Line by Line


$file = fopen("example.txt", "r");
while(!feof($file)) {
   echo fgets($file) . "
"; } fclose($file);

Real-Life Example

User Activity Logging System

Imagine you are building a website and want to track user activity like login times.


$file = fopen("log.txt", "a");
$log = "User logged in at: " . date("Y-m-d H:i:s") . "\n";
fwrite($file, $log);
fclose($file);

How it works:

  • Every time a user logs in, a new entry is added to log.txt.
  • This helps in tracking user behavior and debugging issues.

Another real-life use case is storing form submissions:


$name = "John";
$email = "john@example.com";
$file = fopen("users.txt", "a");
$data = "Name: $name, Email: $email\n";
fwrite($file, $data);
fclose($file);

Common Mistakes

1. Not Closing Files

Forgetting to close files can lead to memory leaks.

Wrong:


$file = fopen("file.txt", "r");
// No fclose()

✔️ Correct:


fclose($file);

2. Using Wrong File Mode

Using “w” instead of “a” can overwrite existing data.


3. Not Checking File Existence

Trying to open a non-existent file in read mode causes errors.

✔️ Solution:


if(file_exists("file.txt")) {
   $file = fopen("file.txt", "r");
}

4. Ignoring Error Handling

Not checking if fopen() fails.

✔️ Best Practice:


$file = fopen("file.txt", "r") or die("Unable to open file!");

5. Incorrect File Permissions

Sometimes files cannot be accessed due to permission issues.

Conclusion

File handling in PHP is a powerful feature that enables developers to manage data efficiently without always relying on databases. From reading and writing files to handling logs and uploads, PHP provides flexible and easy-to-use functions for all file operations.

By mastering file handling, you can build dynamic and efficient applications. However, it is important to follow best practices such as proper file closing, error handling, and correct file modes to avoid common mistakes.

Related PHP Tutorials