PHP Tutorial
Estimated reading: 4 minutes 356 views

PHP File Handling – Read, Write, Modify, and Manage Files in PHP


Introduction – Why PHP File Handling Matters

File handling is essential in PHP for tasks like reading logs, uploading content, storing form data, and managing assets dynamically. PHP provides a robust set of file system functions to open, read, write, modify, and delete files, making it a critical skill for backend developers.


Topics Covered

Topic Description
PHP File Handling OverviewBasic understanding of file operations in PHP
PHP Open / Read / Write / AppendOpen a file and perform common file I/O
PHP File Existence / Copy / Delete / DownloadCheck file status and perform basic file manipulations
PHP Handle CSV FileCreate and read CSV data with PHP
PHP File PermissionsChange and manage file permission settings
PHP Create DirectoryMake new folders using PHP
PHP Listing FilesRead file lists from a directory
PHP File InclusionInclude and reuse files dynamically with include() and require()

PHP File Handling Overview

PHP allows you to interact with the file system using built-in functions like fopen(), fread(), fwrite(), unlink(), and more.

Key Functions

  • fopen() – open a file
  • fread() – read a file
  • fwrite() – write to a file
  • fclose() – close the file

PHP Open / Read / Write / Append

Opening a File

$file = fopen("example.txt", "r");
  • "r" – open for reading.
  • "w" – write only, erases existing content.
  • "a" – write only, appends to the end.

Reading File Content

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

Writing to a File

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

Appending Data

$file = fopen("example.txt", "a");
fwrite($file, "\nNew line added!");
fclose($file);

PHP File Existence / Copy / Delete / Download

Check File Exists

if (file_exists("example.txt")) {
    echo "File found!";
}

Copy a File

copy("example.txt", "backup.txt");

Delete a File

unlink("example.txt");

Download a File (Force)

header('Content-Disposition: attachment; filename="example.txt"');
readfile("example.txt");

PHP Handle CSV File

Create a CSV

$data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]];
$file = fopen("data.csv", "w");

foreach ($data as $row) {
    fputcsv($file, $row);
}
fclose($file);

Read a CSV

$file = fopen("data.csv", "r");
while (($row = fgetcsv($file)) !== false) {
    print_r($row);
}
fclose($file);

PHP File Permissions

Change File Permissions

chmod("example.txt", 0644);
  • 0644: Read/write for owner, read-only for others.

Check Permissions

echo substr(sprintf('%o', fileperms('example.txt')), -4);

PHP Create Directory

Create Directory

mkdir("myfolder");

Create Directory with Permissions

mkdir("myfolder", 0755, true);  // recursive

PHP Listing Files

List All Files in a Directory

$files = scandir("myfolder");
print_r($files);

Filter Files

foreach (scandir("myfolder") as $file) {
    if (is_file("myfolder/$file")) {
        echo "$file\n";
    }
}

PHP File Inclusion

Include Files

include("header.php");

Require Files (stop on failure)

require("config.php");

Differences:

  • include() gives a warning if the file is not found.
  • require() gives a fatal error.

Summary – Recap & Next Steps

With PHP’s powerful file handling capabilities, you can build secure, dynamic, and modular applications that interact with the file system and user uploads efficiently.

Key Takeaways:

  • Master fopen(), fread(), fwrite() for file I/O.
  • Use checks like file_exists() and unlink() for robust logic.
  • Work with CSVs, directories, and permissions with built-in functions.

Real-World Relevance: File handling is crucial in CMS systems, blog platforms, reporting tools, user uploads, and backups.

Next Up: Explore PHP Sessions & Cookies to manage user data between requests.


FAQs – PHP File Handling


Can PHP create and delete folders?
Yes, use mkdir() to create and rmdir() to delete directories.


What is the difference between include and require?
include() gives a warning if the file is missing, while require() throws a fatal error and stops script execution.


How do I check if a file exists in PHP?
Use file_exists("filename.txt") to verify file presence before reading or writing.


Can I use PHP to force file downloads?
Yes, use the Content-Disposition header along with readfile().


How do I read CSV files in PHP?
Use fgetcsv() inside a loop to read CSV rows as arrays.


Share Now :
Share

📂 PHP File Handling

Or Copy Link

CONTENTS
Scroll to Top