Reading files is a fundamental part of server-side programming. While readfile() is good for simple output, fopen() provides much more control over how you interact with the file system.
fopen() FunctionTo open a file, use fopen(). You must specify the filename and the mode (how you want to open it).
| Mode | Description |
|---|---|
r | Read only. Pointer starts at the beginning. |
r+ | Read/Write. Pointer starts at the beginning. |
w | Write only. Overwrites existing content. |
a | Append. Pointer starts at the end. |
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
?>
fread()The fread() function reads from an open file. It takes two parameters: the file handle and the maximum number of bytes to read.
<?php
echo fread($myfile, filesize("webdictionary.txt"));
?>
fclose()Always close your files using fclose() to free up server resources.
<?php
fclose($myfile);
?>
fgets()For large files, it is better to read line by line using a loop and the feof() (End Of File) check.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
fgetc() if you need to read a file character by character, which is useful for custom parsing logic.
fopen() opens a connection to a file.r, w, and a define the access type.fread() reads a specific number of bytes.fgets() reads until it hits a newline character.fclose() is mandatory for good resource management.