Many real applications need to read data from files, write logs, or let users upload documents and images. PHP File Handling gives you the built-in tools to open, read, write, and manage files directly from your scripts, without relying on a database for every single task.

This is Tutorial 5 of 10 in our PHP Advanced series. You will learn how to open and close files, read and write content, and safely process file uploads submitted through a form.

What is PHP File Handling?

PHP File Handling refers to a set of built-in functions that let your script interact directly with files stored on the server. This includes creating new files, reading existing content, appending data, and accepting files uploaded by users through HTML forms.

Opening a File with fopen()

Before reading or writing anything, you must open a file using fopen(), which requires a file path and a mode describing what you intend to do with it.

<?php
$file = fopen("notes.txt", "w");
?>

The “w” mode opens a file for writing, creating it if it does not already exist, and erasing any existing content inside it. PHP File Handling supports several other modes depending on your needs.

Mode Description
r Read only, file must already exist
w Write only, erases existing content
a Append, adds new content to the end
r+ Read and write, file must already exist

Writing to a File

Once a file is open in write mode, you use fwrite() to insert content into it, followed by fclose() to properly close the file and save the changes.

<?php
$file = fopen("notes.txt", "w");
fwrite($file, "This is my first line of text.");
fclose($file);
?>

Closing a file after every PHP File Handling operation is important, since leaving files open unnecessarily can lead to data not being saved correctly or files becoming locked.

Appending to a File

If you want to add new content without erasing what already exists, open the file using “a” mode instead of “w”.

<?php
$file = fopen("notes.txt", "a");
fwrite($file, "\nThis is an additional line.");
fclose($file);
?>

Reading a File

To read content from a file, open it in “r” mode and use fread() along with filesize() to read the entire contents at once.

<?php
$file = fopen("notes.txt", "r");
$content = fread($file, filesize("notes.txt"));
fclose($file);

echo $content;
?>

This pattern of PHP File Handling — combining fread() with filesize() — ensures you read the exact number of bytes the file actually contains, avoiding leftover or truncated data.

A Simpler Way: file_get_contents() and file_put_contents()

PHP also provides shortcut functions that skip the fopen and fclose steps entirely, making simple PHP File Handling tasks much quicker to write.

<?php
file_put_contents("notes.txt", "Quick write example.");

$content = file_get_contents("notes.txt");
echo $content;
?>

For straightforward reading and writing tasks, file_get_contents() and file_put_contents() are often preferred over manually managing fopen(), fwrite(), and fclose() separately.

Checking if a File Exists

Before reading or deleting a file, it is good practice to confirm it actually exists using file_exists(), preventing errors when the file is missing.

<?php
if (file_exists("notes.txt")) {
    echo "File found.";
} else {
    echo "File does not exist.";
}
?>

Deleting a File

The unlink() function permanently removes a file from the server. Always confirm the file exists first before attempting to delete it.

<?php
if (file_exists("notes.txt")) {
    unlink("notes.txt");
    echo "File deleted.";
}
?>

Handling File Uploads

PHP File Handling extends beyond local files to accepting uploads submitted through HTML forms. Uploaded file data becomes available through the $_FILES superglobal, which behaves similarly to $_POST but specifically for file data.

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="userfile">
    <input type="submit" value="Upload">
</form>

Notice the enctype attribute — without it, file uploads will not work correctly, regardless of how the PHP code is written.

Processing an Uploaded File

On the receiving PHP page, move_uploaded_file() transfers the file from its temporary location into a permanent folder on your server.

<?php
if (isset($_FILES["userfile"])) {
    $targetPath = "uploads/" . basename($_FILES["userfile"]["name"]);

    if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $targetPath)) {
        echo "File uploaded successfully.";
    } else {
        echo "Upload failed.";
    }
}
?>

Real applications also validate file type and size before moving an uploaded file, preventing users from uploading unwanted or oversized content. For complete technical documentation, refer to the official PHP file upload manual.

What’s Next?

You now understand PHP File Handling — opening, reading, writing, appending, deleting files, and processing uploads through $_FILES. In the next tutorial, we will connect PHP to a MySQL database using PDO, a major milestone toward building dynamic, data-driven applications.

If you missed the previous lesson, check out Tutorial 4: PHP Error Handling Guide, or explore all lessons in our PHP category.

Practice Exercise

Complete the following tasks to reinforce what you learned in this tutorial:

  • Create a PHP file named file-handling-practice.php
  • Write a script that creates a text file and writes three lines of your choice into it
  • Write a separate script that reads and displays the full content of that file
  • Modify your script to append a fourth line without erasing the existing content
  • Use file_exists() to check if the file exists before attempting to read it
  • Create a simple HTML form that allows a user to upload an image file
  • Write the PHP code to move the uploaded file into an “uploads” folder and display a success message

Bonus Challenge: Modify your file upload script to check the uploaded file’s extension using pathinfo(), and only allow files with jpg, png, or pdf extensions — displaying an error message for any other file type.

About Author

Arshad Sultan

Arshad Sultan is the Founder of Tutorials Ocean and a Technical Architect & Full-Stack Developer with 15+ years of experience in PHP, Laravel, CRM development, API integrations, and AI-powered automation. He also runs Rapid Code, a software and AI automation agency, and has trained hundreds of students across Karachi's IT institutes since 2010.

Leave a Reply

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