File handling in PHP involves working with files on the server, including reading from files, writing to files, and performing various operations such as creating, deleting, and modifying files. Here's an overview of how to handle files in PHP:
You can open a file using fopen(), which returns a file pointer resource.
$myfile = fopen("example.txt", "r") or die("Unable to open file!");
Always remember to close the file when you're done with it.
fclose($myfile);
Use file_get_contents() to read the entire contents of a file into a string.
$content = file_get_contents("example.txt");
echo $content;
Use fgets() to read a single line from a file.
$myfile = fopen("example.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
Use fwrite() to write to a file.
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Smith\n";
fwrite($myfile, $txt);
fclose($myfile);
$myfile = fopen("existingfile.txt", "a") or die("Unable to open file!");
$txt = "New data appended.\n";
fwrite($myfile, $txt);
fclose($myfile);
You can check if a file exists using file_exists().
if (file_exists("example.txt")) {
echo "File exists.";
} else {
echo "File does not exist.";
}
To delete a file, use unlink().
$file = "file-to-delete.txt";
if (file_exists($file)) {
unlink($file);
echo "File deleted.";
} else {
echo "File does not exist.";
}
Always handle errors properly, especially when working with files. You can use feof(), feof(), and other file functions within if conditions to check for errors and handle them gracefully.
Example - Reading and Displaying File Contents:
$filename = "example.txt";
if (file_exists($filename)) {
$file = fopen($filename, "r") or die("Unable to open file!");
while (!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
} else {
echo "File not found!";
}
This code reads the contents of example.txt line by line and displays them. It also checks if the file exists before attempting to open it.