File read and write operations refer to reading from and writing to files using a computer. Simply put, programs can operate on the computer's file system through programming languages, enabling opening, reading, writing, and closing files.
In PHP, the fopen function is used to open files, and fclose is used to close files. Each opened file should be closed promptly to avoid wasting system resources.
When opening a file, you need to specify the file path and the mode. The file path can be relative or absolute. Common opening modes include:
$file_handle = fopen("file_path", "mode");
Examples of modes:
After completing operations, use fclose to close the file and free resources:
fclose($file_handle);
Once a file is opened, you can read from or write to it.
PHP supports two ways to write data: overwrite existing content or append to it.
Use fwrite to write content while opening the file in w mode, which overwrites existing content:
$file_handle = fopen("file_path", "w");
fwrite($file_handle, "Hello World!");
fclose($file_handle);
Notes:
Open the file in append mode (a) to add content at the file's end:
$file_handle = fopen("file_path", "a");
fwrite($file_handle, "Hello World!");
fclose($file_handle);
Note: If the file doesn't exist, the a mode will create it automatically.
Use fgets to read a file line by line:
$file_handle = fopen("file_path", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
// Process $line
}
fclose($file_handle);
Explanation:
File operations may encounter errors like missing files or insufficient permissions, which require proper handling.
PHP offers die and exit functions to output error messages and terminate script execution.
$file_handle = fopen("file_path", "r");
if (!$file_handle) {
die("Unable to open file");
}
while (!feof($file_handle)) {
$line = fgets($file_handle);
// Process the line
}
fclose($file_handle);
If the file cannot be opened, the script outputs "Unable to open file" and stops executing.
This article introduced the basic PHP file read and write operations, including opening and closing files, writing and reading file content, and common error handling techniques, helping you efficiently manage files in PHP.