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.
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).
PHP provides several ways to read files, including:
while (!feof($file)) {
$line = fgets($file);
echo $line . "<br>";
}
$content = fread($file, filesize("test.txt"));
echo $content;
After finishing the read operation, always close the file to free system resources:
fclose($file);
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.
You can write data to a file using either fputs() or fwrite().
fputs($file, "Hello, World!");
fwrite($file, "Hello, World!");
After finishing the write operation, remember to close the file:
fclose($file);
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);
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.