File handling is a fundamental task in PHP development. Whether you're logging data, storing configuration, or managing user uploads, working with files is essential. This article offers a structured explanation of how to open, read, write, and manage files in PHP, supported by practical code examples.
The fopen() function is used to open files. Here's a basic syntax example:
$handle = fopen("file.txt", "r");
This code opens the file file.txt in read-only mode and stores the file handle in the $handle variable. PHP supports various file modes, such as:
After completing file operations, always close the file using fclose() to free system resources:
fclose($handle);
To read data from a file, use the fread() function, which reads a specified number of bytes:
$content = fread($handle, filesize("file.txt"));
This code reads the entire file and stores it in the $content variable. If you prefer reading line by line, use fgets() with a loop:
while (!feof($handle)) {
$line = fgets($handle);
echo $line;
}
Use the fwrite() function to write data to a file. Make sure the file is opened in write or append mode:
$content = "Hello, world!";
fwrite($handle, $content);
The rename() function lets you rename a file:
rename("file.txt", "newfile.txt");
Use the copy() function to duplicate a file:
copy("file.txt", "copy.txt");
To remove a file, use unlink():
unlink("file.txt");
You can check whether a file exists using file_exists() and take action accordingly:
if (file_exists("file.txt")) {
echo "The file exists!";
} else {
echo "The file does not exist!";
}
This article covered essential PHP file operations, including opening, reading, writing, renaming, copying, deleting, and checking file existence. Mastering these functions allows you to manage file-based data more effectively and write more robust and flexible applications.