PHP is a powerful server-side scripting language widely used for web development. File handling is one of its fundamental features, allowing developers to create, read, write, modify, and delete files easily. This guide explains PHP's most common file handling functions in detail.
In PHP, files are opened using the fopen() function. The syntax is as follows:
$file = fopen("file_path", "mode");Here, “file_path” specifies the path to the file, and “mode” determines how the file is opened. Common modes include:
After performing operations, close the file using the fclose() function:
fclose($file);Properly opening and closing files prevents resource leaks and data corruption.
PHP provides several functions for reading files. The two most commonly used are fread() and fgets().
The fread() function reads a specific number of bytes from an open file:
$content = fread($file, $length);The fgets() function reads one line at a time, making it ideal for reading text files:
$content = fgets($file);To read multiple lines, simply loop through fgets() until reaching the end of the file.
To write content to a file, use fwrite():
fwrite($file, $content);This function writes a string to the file and is often used for logging or storing data.
Beyond basic reading and writing, PHP offers various functions to manage files—such as renaming, deleting, and copying.
Rename a file using rename():
rename("old_file_path", "new_file_path");Delete a file with unlink():
unlink("file_path");Copy a file with copy():
copy("source_file_path", "destination_file_path");You can also get the size of a file using filesize():
$size = filesize("file_path");And check the last modification time using filemtime():
$time = filemtime("file_path");File operations may fail due to missing files or insufficient permissions. To make your program more robust, use a try-catch block to handle exceptions:
try {
// File operation code
} catch (Exception $e) {
// Exception handling logic
}By catching exceptions, you can safely manage errors and prevent unexpected program crashes.
This article introduced the essential PHP file handling functions, including opening, closing, reading, writing, renaming, deleting, copying, and handling exceptions. Understanding these functions will help developers efficiently manage files and build more reliable web applications.