In PHP, you can open and read the contents of a file using the fopen()
, fread()
, and fclose()
functions. Here's an example:
<?php
// Open the file (replace "example.txt" with your file name and path)
$handle = fopen("example.txt", "r");
// Check if the file was opened successfully
if ($handle) {
// Read the contents of the file
$contents = fread($handle, filesize("example.txt"));
// Output the contents
echo $contents;
// Close the file
fclose($handle);
} else {
echo "Unable to open the file.";
}
?>
In the above example, we first open the file using the fopen()
function. The first argument is the name and path of the file, and the second argument is the mode in which we want to open the file ("r" for reading in this case).
After opening the file, we check if it was opened successfully. If it was, we proceed to read the contents of the file using the fread()
function. The first argument is the file handle returned by fopen()
, and the second argument is the number of bytes to read. In this case, we use filesize()
to determine the size of the file and read the entire file contents.
Finally, we output the contents and close the file using the fclose()
function.
Remember to replace "example.txt" with the appropriate file name and path for your situation.