Current Location: Home> Latest Articles> Complete Guide to PHP File Reading and Writing: Common Functions Explained with Practical Tips

Complete Guide to PHP File Reading and Writing: Common Functions Explained with Practical Tips

gitbox 2025-06-07

1. File Reading Techniques

1.1 fopen() Function

The fopen() function opens a file and can be used to read its content or write new data. It requires two parameters: the filename and the mode (read, write, append, etc.). For example, the following code opens a file and reads it line by line:


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

Here, a while loop with fgets() reads each line of the file. The feof() function checks if the end of file has been reached, and fclose() closes the file handle.

1.2 fread() Function

To read the entire file content at once, use fread(). It requires the file handle and the number of bytes to read as parameters, like this:


$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);

The code uses filesize() to get the file size, then fread() reads that many bytes.

1.3 file() Function

The file() function reads the file into an array where each element is a line, which is useful for line-by-line processing of text files. Example:


$file = file("example.txt");
foreach ($file as $line) {
  echo $line."";
}

A foreach loop outputs each line from the array.

1.4 file_get_contents() Function

file_get_contents() is the simplest and quickest way to read the entire file, returning its content as a string. Example:


$file = file_get_contents("example.txt");
echo $file;

This function returns the file content directly and is ideal for reading small files quickly.

2. File Writing Techniques

2.1 fwrite() Function

fwrite() writes data to a file, requiring a file handle and the string to write. Example:


$file = fopen("example.txt", "w");
fwrite($file, "Hello World!");
fclose($file);

Opening a file with mode "w" overwrites the existing content. Use mode "a" to append instead.

2.2 file_put_contents() Function

file_put_contents() is a convenient way to write a string directly to a file, requiring only the filename and content, like this:


file_put_contents("example.txt", "Hello World!");

If the file does not exist, it will be created automatically.

3. Summary

PHP offers various functions for file reading and writing. Commonly used ones include fopen(), fread(), file(), and file_get_contents() for reading, as well as fwrite() and file_put_contents() for writing. Pay attention to file permissions to avoid errors caused by insufficient access rights. Generally, it is recommended to use file_get_contents() and file_put_contents() first due to their simplicity, efficiency, and maintainability.