PHP File Handling: Reading and Writing Files with Ease
Opening and Closing Files
Before performing any file operations, you must open the file using the fopen function. This function takes two parameters: the file path and the mode in which the file should be opened. The mode determines whether the file is read-only, write-only, or both, and whether the file is created if it doesn't exist.
$handle = fopen("example.txt", "r");
if ($handle) {
// File operations here
fclose($handle);
}
| Mode | Description |
|---|---|
r | Open for reading only. The file pointer starts at the beginning of the file. |
w | Open for writing only. Creates the file if it doesn't exist, or truncates it if it does. |
a | Open for writing only. The file pointer starts at the end of the file. |
r+ | Open for reading and writing. The file pointer starts at the beginning. |
w+ | Open for reading and writing. Creates the file if it doesn't exist, or truncates it if it does. |
a+ | Open for reading and writing. The file pointer starts at the end of the file. |
Reading from Files
Once a file is opened, you can read its contents using functions like fread, fgets, or file_get_contents. fread reads a specified number of bytes, while fgets reads a single line at a time.
$handle = fopen("example.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
Alternatively, file_get_contents provides a concise way to read an entire file into a string:
$content = file_get_contents("example.txt");
echo $content;
Writing to Files
To write data to a file, you can use fwrite or file_put_contents. fwrite writes a string to a file, while file_put_contents simplifies the process by handling the opening, writing, and closing of the file automatically.
$handle = fopen("example.txt", "w");
if ($handle) {
fwrite($handle, "Hello, world!");
fclose($handle);
}
Using file_put_contents:
file_put_contents("example.txt", "Hello, world!");
If you want to append data to a file instead of overwriting it, use the a mode:
file_put_contents("example.txt", "Appended line.\n", FILE_APPEND);
Best Practices and Security Considerations
When working with files, always ensure that the file path is valid and that the file is accessible. Avoid using user-provided input directly as a file path to prevent security vulnerabilities such as directory traversal attacks. Always validate and sanitize user input before using it in file operations.
For example, to safely read a file based on user input:
$filename = basename($_GET['file']);
if (is_file($filename)) {
echo file_get_contents($filename);
} else {
echo "File not found.";
}