Working with files in PHP involves opening, reading, and closing files. Here's a simple example of how to do this:
You can open a file using fopen(). This function takes two parameters: the filename and the mode (how you want to open the file).
$filename = "example.txt";
$file = fopen($filename, "r") or die("Unable to open file!");
You can use file_get_contents() to read the entire contents of a file into a string.
$content = file_get_contents($filename);
echo $content;
If you want to read the file line by line, use fgets() inside a loop until the end of the file.
$file = fopen($filename, "r") or die("Unable to open file!");
while(!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
Always remember to close the file when you are done with it, using fclose().
fclose($file);
Here's a complete example that reads the contents of a file line by line and then closes the file:
<?php
$filename = "example.txt";
$file = fopen($filename, "r") or die("Unable to open file!");
while(!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
?>
In this example:
Remember to handle errors gracefully when working with files, especially when opening and reading them, as failure to open a file could cause your script to terminate unexpectedly.