Current Location: Home> Latest Articles> PHP File Handling Techniques: Master Common Read and Write Methods

PHP File Handling Techniques: Master Common Read and Write Methods

gitbox 2025-06-12

Introduction

PHP is a widely-used programming language in web development, offering powerful file handling capabilities. It enables easy reading, writing, and management of files. In this article, we will share common PHP file handling techniques to help developers perform file operations more efficiently.

Reading Files

Opening a File

In PHP, we use the fopen()

Reading from a File

Once the file is opened, you can use the following functions to read the content:

  • fread($file, $length): Reads the specified number of bytes from the file.
  • fgets($file): Reads a single line from the file.
  • fgetc($file): Reads a single character from the file.

Here’s an example of reading file content:


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

Closing the File

After reading a file, it is important to close it using the fclose() function to release system resources.


fclose($file);

Writing to Files

Opening a File

Writing to a file is similar to reading, but you need to specify a write mode when opening the file. If the file does not exist, PHP will create it.


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

Writing to a File

Once the file is opened, you can use the following functions to write content to it:

  • fwrite($file, $string): Writes the specified string to the file.
  • fputs($file, $string): Identical to fwrite().

Here’s an example of writing to a file:


fwrite($file, "Hello World!");

Closing the File

After writing to a file, you should always close it using fclose().


fclose($file);

Common Issues

1. How to Check if a File Exists?

You can use the file_exists() function to check if a file exists.


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

2. How to Read Large Files?

To avoid memory overflow, you can read large files in chunks. By setting the chunk size, you can control memory usage.


$file = fopen("example.txt", "r");
$chunk_size = 1024;  // Read 1KB at a time
$read_times = 0;

while (!feof($file)) {
  $chunk = fread($file, $chunk_size);
  echo $chunk;
  $read_times++;
}

fclose($file);
echo "File has been read " . $read_times . " times.";

3. How to Append Content to a File?

You can open the file in a or a+ mode to append content to the end of the file.


$file = fopen("example.txt", "a");
fwrite($file, "Appended content");
fclose($file);

Conclusion

This article introduced the essential PHP file handling operations, such as file reading, writing, and closing. In actual development, file operations are a crucial part, and mastering these techniques will help you manage files more efficiently in your projects.