PHP File Handling
File handling is an important part of any web application. You often need to open and process a file for different tasks.
1. Opening and Closing Files
The fopen() function is used to open files. It requires two arguments: the file name and the mode.
Modes:
r: Open for reading only.w: Open for writing only. Clears file content or creates a new file.a: Open for writing only. Appends to end of file or creates a new file.
The fclose() function is used to close an open file.
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// ... code to read file ...
fclose($myfile);
2. Reading Files
readfile(): Reads a file and writes it to the output buffer.fread(): Reads from an open file.fgets(): Reads a single line from a file.
$myfile = fopen("webdictionary.txt", "r");
echo fread($myfile, filesize("webdictionary.txt"));
fclose($myfile);
3. Writing to Files
The fwrite() function is used to write to a file.
$myfile = fopen("newfile.txt", "w");
$txt = "John Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
4. Checking if File Exists
Use file_exists() to check if a file or directory exists before trying to access it.
if (file_exists("test.txt")) {
echo "File found.";
} else {
echo "File not found.";
}