PHP File Open/Read
In PHP, you can open and read files using the fopen()
and fread()
functions. This allows you to access the content of files stored on the server.
Opening a File
<?php
$file = fopen("example.txt", "r"); // Open the file for reading
if ($file) {
// File opened successfully
echo "File opened successfully!";
} else {
echo "Failed to open the file.";
}
fclose($file); // Close the file
?>
Explanation: This example demonstrates how to open a file in read mode using fopen()
. Always remember to close the file after opening it using fclose()
.
Reading from a File
<?php
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt")); // Read the entire file
fclose($file);
echo $content; // Display the content
?>
Explanation: This example reads the entire content of the file using fread()
and displays it. The filesize()
function is used to get the size of the file.