Current Location: Home> Latest Articles> Complete Guide to PHP File Handling: Master File Reading and Writing Techniques

Complete Guide to PHP File Handling: Master File Reading and Writing Techniques

gitbox 2025-06-15

Introduction to PHP File Handling

PHP is a powerful server-side scripting language widely used in web development. File operations—such as reading logs, saving user input, or processing configuration files—are common tasks. Knowing how to properly read from and write to files in PHP can greatly enhance your development efficiency and the reliability of your applications.

How to Read File Content in PHP

Method 1: Using fopen() and fgets()

You can use fopen() to open a file and fgets() to read its content line by line. Here's a basic example:

<?php
$file = fopen("example.txt", "r");
while(!feof($file)) {
  $line = fgets($file);
  echo $line . "";
}
fclose($file);
?>

Note: The "r" parameter opens the file in read-only mode. Always use fclose() to close the file handle after you're done to free up system resources.

Method 2: Using file_get_contents()

The file_get_contents() function is a simpler way to read the entire content of a file at once:

<?php
$content = file_get_contents("example.txt");
echo $content;
?>

This method works best with small to medium-sized text files. For large files, reading line by line is more memory-efficient.

How to Write Data to a File in PHP

Method 1: Using fopen() and fwrite()

Open a file with fopen() and write content to it using fwrite():

<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello World.");
fclose($file);
?>

Warning: The "w" mode overwrites the file if it exists. Always be careful when writing to files using this mode.

Method 2: Using file_put_contents()

The file_put_contents() function offers a cleaner, more modern way to write data to a file:

<?php
$file = "example.txt";
$data = "Hello World.";
file_put_contents($file, $data);
?>

This method is especially useful for writing small chunks of data or saving simple configurations quickly.

Conclusion

Understanding how to read from and write to files is a core part of working with PHP. Each method has its own use case—from line-by-line reading to quick file writes. Choosing the right approach will help you build more efficient and robust PHP applications.