How can PHP be used to open and read the contents of a file?
To open and read the contents of a file using PHP, you can use the `fopen()` function to open the file, `fread()` function to read the contents, and `fclose()` function to close the file handle once you are done. Make sure to handle any errors that may occur during the process.
$filename = 'example.txt';
$handle = fopen($filename, 'r');
if ($handle) {
$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
} else {
echo "Unable to open file.";
}
Keywords
Related Questions
- What is the best method to compare two arrays in PHP and find the elements that are present in one array but not in the other?
- What are some best practices for handling user input in PHP to avoid issues with data types, such as converting numbers to strings?
- How can the include_path setting impact PHP includes?