Introduction to PHP File Handling

Introduction

File handling in PHP allows you to work with files on the server, such as reading data from a file, writing content into a file, uploading files, and managing file permissions. This is useful when building features like log files, storing user data, saving settings, or reading configuration files.

In this tutorial, you’ll learn the basics of PHP file handling with simple and practical examples.

What You’ll Learn

  • How to read files in PHP
  • How to write and append data
  • Important file handling functions
  • Real-world logging example
  • Common mistakes to avoid

What Is File Handling in PHP?

File handling means manipulating files using PHP code, such as:

  • Creating files
  • Reading data from a file
  • Writing data to a file
  • Append data to files
  • Uploading files
  • Logging errors
  • Saving user data
  • Delete a file
  • Check if a file exists

PHP provides built-in functions to handle files easily and efficiently.

Why File Handling Is Important

File handling is used in many practical situations:

  • Saving logs and reports
  • Reading configuration files
  • Uploading images and documents
  • Creating backups
  • Storing temporary data
  • Working with CMS and frameworks

Even WordPress uses file handling internally for themes, plugins, and uploads.

Common PHP File Functions

Here are some commonly used PHP file functions:

FunctionPurpose
fopen()Opens a file
fread()Reads file data
fwrite()Writes data to a file
fclose()Closes a file
file_get_contents()Reads entire file
file_put_contents()Writes data quickly
unlink()Deletes a file
file_exists()Checks if file exists

We will learn these functions one by one in upcoming lessons.

Basic File Handling Workflow

Most file operations follow this simple flow:

  1. Open the file
  2. Read or write data
  3. Close the file

Example flow:

$file = fopen("example.txt", "r");
// read or write
fclose($file);

How to Error Handling in PHP Files

You can handle file opening errors by using the die() function in PHP.

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

File Modes in PHP

When opening a file, PHP uses modes to define how the file should be accessed.

Some common modes:

ModeMeaning
rRead only
wWrite (overwrite)
aAppend
r+Read & write
w+Write & read

You don’t need to memorize them now — we’ll use them practically later.

How to Read a File in PHP

The fopen() function is used to open a file in read mode:

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

Easier Way

$content = file_get_contents("data.txt");
echo $content;

Reading very large files using fread() can cause memory issues.

How to Write to a File

$file = fopen("data.txt", "w");
fwrite($file, "Hello PHP!");
fclose($file);

Append Data to File

file_put_contents("data.txt", "New line\n", FILE_APPEND);

Checking If a File Exists

if (file_exists("data.txt")) {
    echo "File exists";
} else {
    echo "File not found";
}

Deleting a File

unlink("data.txt");

File Handling Example (Real World)

$message = "User logged in at " . date("Y-m-d H:i:s") . "\n";
file_put_contents("log.txt", $message, FILE_APPEND);

This is useful for:

  • activity logs
  • error logs
  • tracking user actions

Difference Between fopen() and file_get_contents()

FunctionWhen to Use
fopen()Large files / step-by-step control
file_get_contents()Small files / quick read

Important Things to Remember

  • Files must have proper permissions
  • Always close files after use
  • Handle errors carefully
  • Never trust user-uploaded files without validation

File handling should always be done securely.

Common Beginner Mistakes

  • ❌ Forgetting to close file with fclose()
  • ❌ Using wrong file mode (w deletes old data)
  • ❌ Not checking if file exists
  • ❌ No permission to write files
  • ❌ Writing user input directly without validation

File Permissions (Important)

Your server must allow PHP to write files.

  • On Linux servers, permissions like 755 or 775 are commonly used for folders.
  • If PHP cannot write files, you may see permission errors.

Security Tips

  • Never allow users to choose file paths directly
  • Validate file names
  • Store files outside public folders when possible
  • Don’t write sensitive data in plain text
  • Always sanitize user input

Summary

  • PHP file handling lets you work with server files
  • It is essential for real-world PHP projects
  • PHP provides many built-in file functions
  • Understanding file handling improves backend skills

Practice Tasks

  1. Create a file notes.txt
  2. Write a PHP script to save a message into the file
  3. Append a new line each time the page reloads
  4. Display the file content on the page
  5. Try deleting the file and recreate it

Now that you understand the basics of PHP file handling, let’s move to the next step:

👉 Reading Files in PHP

In the next tutorial, you will learn how to read file content in detail using different PHP functions.

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *