File Handling in PHP

File handling is a crucial aspect of web development, allowing developers to read, write, and manipulate files using PHP. Whether you need to upload files, retrieve data from text files, or generate dynamic files, understanding the principles and techniques of file handling in PHP is essential. In this article, I will explore the various file handling functions and methods available in PHP, along with best practices and examples to help you master this fundamental skill.

$filePath = “file_handling_example.txt”;

// Reading from a file
$file = fopen($filePath, “r”) or die(“Unable to open file!”);

// Read and display each line from the file
while (!feof($file)) {
$line = fgets($file);
echo $line;
}

// Close the file
fclose($file);

// Writing to a file
$data = “Hello, PHP!”;

// Open the file in write mode
$file = fopen($filePath, “w”) or die(“Unable to open file!”);

// Write data to the file
fwrite($file, $data);

// Close the file
fclose($file);

// Reading the updated file
$file = fopen($filePath, “r”) or die(“Unable to open file!”);

// Read and display the updated content from the file
while (!feof($file)) {
$line = fgets($file);
echo $line;
}

// Close the file
fclose($file);

Explanation of above example:

1. Opening and Closing Files
Before performing any file operations, you need to open the file using the “fopen()” function. It takes two parameters: the file path and the mode in which you want to open the file (e.g., read, write, append). Once you are done with the file, it’s important to close it using the “fclose()” function to free up system resources.

2. Reading from Files
PHP provides multiple functions to read data from files. The “fgets()” function reads a single line from a file, while “fread()” allows you to read a specific number of bytes. Alternatively, “file()” reads the entire file into an array, with each element representing a line. You can also use “fgetc()” to read a single character at a time.

3. Writing to Files
To write data to a file, you can use the “fwrite()” function. It takes the file handle and the data you want to write as parameters. Additionally, “file_put_contents()” provides a convenient way to write data to a file in one line, eliminating the need for explicit file opening and closing.

4. Appending to Files
If you want to add content to an existing file without overwriting its existing content, you can use the “fwrite()” function with the “a” mode, or the “file_put_contents()” function with the “FILE_APPEND” flag.

5. Checking File Existence and File Information
The “file_exists()” function helps determine whether a file exists in the specified path. PHP also provides functions like “is_file()”, “is_dir()”, and “filemtime()” to check if a path points to a regular file, directory, or retrieve the last modified timestamp of a file, respectively.