PHP: How to read and write to a text file

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

In PHP, handling files is a common task that helps persist data across sessions and enhances dynamic content management. This tutorial will guide you through reading from and writing to files using PHP, with concise explanations and practical code examples, from basic file operations to more advanced techniques.

Getting Started with File Handling

File handling in PHP is done using built-in functions. Before you start, ensure you have the appropriate permissions on the file or directory you’re attempting to access.

Opening a File

$fileHandle = fopen('example.txt', 'r');
if (!$fileHandle) {
    die('File open failed!');
}

Reading from a File

To read content:

// Read one line at a time
while ($line = fgets($fileHandle)) {
    echo $line;
}

// Close the file
fclose($fileHandle);

Writing to a File

$fileHandle = fopen('example.txt', 'w');
fwrite($fileHandle, "New content");
fclose($fileHandle);

File Read/Write Operations

Reading Entire File

$content = file_get_contents('example.txt');
echo $content;

Writing to a File in One Go

If the file does not exist, it will be created:

file_put_contents('example.txt', "The entire content of the file.");

Working with CSV Files

$fileHandle = fopen('data.csv', 'r');
while ($data = fgetcsv($fileHandle)) {
    // Process CSV line
}
fclose($fileHandle);

Advanced File Handling Techniques

Using File Streams

PHP’s stream functions provide more control over file I/O operations:

$context = stream_context_create([...]);
$content = file_get_contents('example.txt', false, $context);

Handling Remote Files

PHP can also handle HTTP reads and writes:

$content = file_get_contents('http://example.com');
file_put_contents('http://api.example.com/resource', $body);

Binary File Access

$fileHandle = fopen('example.bin', 'rb');
$data = fread($fileHandle, filesize('example.bin'));
fclose($fileHandle);

Summary

This PHP tutorial provides a thorough walkthrough of file read and write operations, guiding you from basic to more sophisticated techniques. By mastering these skills, you’ll be equipped to manage file-based data effectively within your PHP applications, ensuring your project’s requirements for data persistence and manipulation are successfully met.