PHP Reading and Writing Files

11/22/2025

PHP file reading and writing example for beginners

Go Back

PHP Reading and Writing Files: A Complete Beginner-Friendly Guide

Working with files is an essential part of PHP development. Whether you’re building a logging system, uploading files, exporting reports, or storing user data, PHP provides powerful built-in functions to read, write, append, and manage files easily.

In this tutorial, you’ll learn:

  • How PHP interacts with files

  • How to read files using different methods

  • How to write and append data to files

  • Real-world developer examples

  • Important file-handling functions

  • Common best practices


Why File Handling Is Important in PHP?

File handling is used for:

  • Storing logs (log.txt)

  • Exporting data (report.txt, CSV files)

  • Reading configuration files

  • Saving form submissions

  • Reading templates

  • Processing uploaded files

PHP makes file handling simple with clear functions.


1. Reading Files in PHP

There are multiple ways to read a file. Here are the most commonly used methods.


PHP file reading and writing example for beginners

Method 1: readfile() – Quick Output

Reads and outputs the file content directly to the browser.

readfile("data.txt");

Useful for small files.


Method 2: file_get_contents() – Read Entire File into a String

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

Best when you need file contents stored in a variable.


Method 3: file() – Read File Into an Array Line-by-Line

$lines = file("data.txt");
foreach ($lines as $line) {
    echo $line . "<br>";
}

Great for processing line-based data.


Method 4: fopen() with fread() – Manual File Reading

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

echo $content;

More control over file reading.


2. Writing Files in PHP

You can create new files or write to existing ones.


Method 1: file_put_contents() – Easiest Way

$data = "Hello, this is a new message!";
file_put_contents("output.txt", $data);

This creates the file if it does not exist.


Append Data Instead of Overwriting

file_put_contents("output.txt", "\nNew Line Added", FILE_APPEND);

Method 2: fwrite() Using fopen()

$handle = fopen("output.txt", "w"); // w = write
fwrite($handle, "Writing using fwrite() function.");
fclose($handle);

Modes like w, a, r+, w+ provide flexibility.


File Modes in fopen()

ModeDescription
rRead only
wWrite (truncate file)
aAppend
r+Read & write
w+Read & write (truncate file)
a+Read & append

3. Checking If File Exists

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

4. Deleting a File

if (file_exists("old.txt")) {
    unlink("old.txt");
}

5. Real-World Example: Saving Form Data to a File

$name = $_POST['name'];
$email = $_POST['email'];

$entry = "Name: $name | Email: $email\n";
file_put_contents("submissions.txt", $entry, FILE_APPEND);

echo "Data saved successfully!";

This is commonly used in feedback forms.


6. Reading JSON File

$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);

print_r($data);

7. Writing JSON File

$data = ["name" => "Shubham", "role" => "Developer"];
file_put_contents("data.json", json_encode($data));

Best Practices for PHP File Handling

  • Always check if a file exists before reading

  • Close file handles after fopen()

  • Use file permissions wisely

  • Sanitize user input when writing to files

  • Avoid handling extremely large files without buffering


Conclusion

PHP provides a powerful set of functions to read, write, append, and manage files easily. Whether you're logging data, processing uploaded files, or exporting reports, mastering PHP file handling is an essential skill for backend development.

Table of content

  • Introduction to Apache Hive
  • Hive Architecture and Components
  • Hive Modes
  • Installation and Setup
    • Installing Hive on Linux/Windows
    • Configuring Hive with Hadoop
    • Verifying the Installation
  • Working with Hive Tables
    • Internal (Managed) Tables
    • External Tables
    • Creating Tables in Hive
    • Altering and Dropping Tables
    • Partitioning in Hive
    • Bucketing in Hive
  • HiveQL Basics
    • SELECT Queries
    • Filtering Data with WHERE
    • Sorting and Grouping Data
    • Using Joins in Hive
  • Advanced Hive Concepts
    • Partition Pruning
    • Dynamic Partitioning
    • Query Optimization in Hive
    • Working with Hive Indexes
    • ACID Transactions in Hive
  • File Formats in Hive
    • Text File
    • ORC (Optimized Row Columnar)
    • Parquet
    • Avro
    • Sequence File
  • Hive Functions
    • Built-in Functions (String, Date, Math)
    • Aggregate Functions
    • User-Defined Functions (UDFs)
  • Integrating Hive with Other Tools
    • Hive and Apache Spark
    • Hive and Pig
    • Hive and HBase
  • Hive Interview Questions
  • Best Practices in Hive
    • Performance Optimization
    • Handling Large Datasets
    • Security and Access Control
  • FAQs and Common Errors in Hive
    • Troubleshooting Hive Issues
    • Frequently Asked Questions
  • Resources and References
    • Official Hive Documentation
    • Recommended Books and Tutorials