Skip to content

PHP File Handling — Complete Guide to Reading and Writing Files

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about PHP File Handling. We cover key concepts, practical examples, and best practices to help you master this topic.

PHP file handling functions read and write files on the server filesystem, supporting text and binary data, CSV Parsing, directory operations, and file metadata.

What You'll Learn

By the end of this tutorial, you'll use fopen/fread/fwrite, file_get_contents/file_put_contents, read and write CSV, manage directories, check file permissions, and handle errors.

Why File Handling Matters

PHP applications read configuration files, Process uploaded files, generate reports, write logs, and manage data files. File handling is fundamental for data persistence and system interaction.

Real-World Use

A log analyzer reads server access logs line by line, parses entries using fgets, extracts error patterns, and writes a summary report to a new file.

File Handling Learning Path

flowchart LR
  A[JSON] --> B[File Handling]
  B --> C[Errors]
  C --> D[Exceptions]
  D --> E[Classes/Objects]
  A --> F{You Are Here}
  style F fill:#f90,color:#fff

Reading Files

<?php
// Read entire file (simple)
$content = file_get_contents("data.txt");
echo $content;

// Read line by line (memory efficient for large files)
$handle = fopen("large-file.log", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        echo $line;
    }
    fclose($handle);
}

Writing Files

<?php
// Write entire file (overwrite)
file_put_contents("output.txt", "Hello, World!\n");

// Append to file
file_put_contents("log.txt", "New entry\n", FILE_APPEND);

// Manual writing
$handle = fopen("data.csv", "w");
fwrite($handle, "Name,Email,Age\n");
fwrite($handle, "Alice,alice@example.com,25\n");
fclose($handle);

CSV Handling

<?php
// Writing CSV
$handle = fopen("users.csv", "w");
fputcsv($handle, ["Name", "Email", "Age"]);
fputcsv($handle, ["Alice", "alice@example.com", 25]);
fputcsv($handle, ["Bob", "bob@example.com", 30]);
fclose($handle);

// Reading CSV
$handle = fopen("users.csv", "r");
$headers = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
    print_r(array_combine($headers, $row));
}
fclose($handle);

Directory Operations

<?php
// Create directory
mkdir("uploads/2026/06", 0755, true);  // recursive

// List files
$files = scandir("uploads");
foreach ($files as $file) {
    if ($file !== "." && $file !== "..") {
        echo $file . "\n";
    }
}

// Check if file or directory exists
if (file_exists("config.php")) {
    echo "Config file exists";
}

File Information

<?php
$path = "document.pdf";
echo filesize($path);     // Size in bytes
echo filemtime($path);    // Last modified timestamp
echo filetype($path);     // file or dir
echo pathinfo($path, PATHINFO_EXTENSION);  // pdf
echo pathinfo($path, PATHINFO_FILENAME);   // document

Common Mistakes

1. Not Checking fopen Return Value

fopen returns false on failure. Always check if ($handle !== false) before reading/writing.

2. Forgetting to Close File Handles

Unclosed handles cause file locks and memory leaks. Always fclose() when done.

3. Not Using Locking for Concurrent Access

Multiple processes writing to the same file causes corruption. Use flock() for file locking.

4. Assuming file_put_contents Is Atomic

Large writes may be interrupted. Write to a temp file and rename atomically.

5. Path Traversal Vulnerabilities

User input in file paths can access files outside the intended directory. Always validate and sanitize paths.

Practice Questions

1. What is the difference between file_get_contents and fopen+fread?

file_get_contents reads the entire file at once (simple but memory-heavy for large files). fopen+fread reads in chunks (memory efficient).

2. How do you append to a file in PHP?

Use file_put_contents($path, $data, FILE_APPEND) or fopen with "a" mode.

3. What does fgetcsv return?

An indexed array of fields from the current CSV row, or false at EOF.

4. How do you safely write to a file in a concurrent environment?

Use flock($handle, LOCK_EX) for exclusive lock, or write to a temp file and rename.

5. Challenge: Write a function that reads a CSV file and returns it as an associative array.

<?php
function csvToArray(string $filePath): array {
    if (!file_exists($filePath)) return [];
    $handle = fopen($filePath, "r");
    $headers = fgetcsv($handle);
    $data = [];
    while (($row = fgetcsv($handle)) !== false) {
        $data[] = array_combine($headers, $row);
    }
    fclose($handle);
    return $data;
}
print_r(csvToArray("users.csv"));

FAQ

What file modes are available in fopen?

r (read), w (write, truncate), a (append), r+ (read/write). Add b for binary mode: 'rb', 'wb'.

How do I read a file backwards?

Read the entire file, explode by newlines, and reverse the array. Or use fseek for large files.

What is the maximum upload file size?

Controlled by upload_max_filesize and post_max_size in php.ini. Default is 2MB-8MB.

How do I check if a directory is writable?

Use is_writable($dirPath). Returns true if PHP can write to the directory.

What is the difference between include and file_get_contents?

include executes PHP code. file_get_contents reads raw content without execution.

Mini Project: Log File Analyzer

Build a log analyzer that reads an access log and generates statistics.

<?php
function analyzeLog(string $logFile): array {
    if (!file_exists($logFile)) return ["error" => "File not found"];
    $handle = fopen($logFile, "r");
    $stats = ["lines" => 0, "errors" => 0, "ips" => []];
    while (($line = fgets($handle)) !== false) {
        $stats["lines"]++;
        if (str_contains($line, "ERROR")) $stats["errors"]++;
        preg_match("/\d+\.\d+\.\d+\.\d+/", $line, $matches);
        if (!empty($matches)) $stats["ips"][$matches[0]] = true;
    }
    fclose($handle);
    $stats["unique_ips"] = count($stats["ips"]);
    return $stats;
}
print_r(analyzeLog("server.log"));

What's Next

PHP Errors PHP Exceptions PHP Classes Objects

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro