Current Location: Home> Latest Articles> PHP File Read and Write Tutorial: Master fopen, fread, fwrite and Common File Handling Methods

PHP File Read and Write Tutorial: Master fopen, fread, fwrite and Common File Handling Methods

M66 2025-10-13

PHP File Read and Write Tutorial

In web development, file operations are one of the most common tasks, such as reading configuration files, saving logs, or generating reports. PHP offers a variety of simple and powerful functions for reading and writing files. This guide will walk you through the key methods and workflow for handling files in PHP.

Reading Files

Before reading a file, you need to open it using the fopen() function. This function takes two parameters: the file path and the file mode.

$file = fopen("test.txt", "r");

The example above opens the file named test.txt in read-only mode (r).

Methods for Reading File Content

PHP provides several ways to read files, including:

  • fgets() function: Reads the file line by line, ideal for processing text files incrementally.
while (!feof($file)) {
    $line = fgets($file);
    echo $line . "<br>";
}
  • fread() function: Reads a specific number of bytes, often used to read an entire file at once.
$content = fread($file, filesize("test.txt"));
echo $content;

After finishing the read operation, always close the file to free system resources:

fclose($file);

Writing Files

Writing to a file follows a similar process. First, open the file with fopen() and specify the appropriate mode:

$file = fopen("test.txt", "w");

The "w" mode opens the file for writing. If the file does not exist, PHP will create it. If it already exists, its contents will be erased before writing.

Methods for Writing File Content

You can write data to a file using either fputs() or fwrite().

  • Using fputs() function:
fputs($file, "Hello, World!");
  • Using fwrite() function:
fwrite($file, "Hello, World!");

After finishing the write operation, remember to close the file:

fclose($file);

Complete Example: Reading and Writing Combined

The following example demonstrates how to read the contents of one file and write them to another file:

// Open the source file
$readFile = fopen("source.txt", "r");

// Open the target file
$writeFile = fopen("target.txt", "w");

// Read and write line by line
while (!feof($readFile)) {
    $line = fgets($readFile);
    fputs($writeFile, $line);
}

// Close both files
fclose($readFile);
fclose($writeFile);

Conclusion

This tutorial introduced the fundamental techniques for handling file operations in PHP, including opening, reading, writing, and closing files. By mastering these functions, developers can efficiently manage data and improve code flexibility for real-world applications.