File Open Or Read in PHP
? File Open or Read in PHP
In PHP, you can open and read files using built-in functions like fopen(), fread(), fgets(), and file_get_contents(). This is useful for processing logs, text files, or displaying stored content.
? 1. Open and Read Entire File – fopen() + fread()
<?php$file = fopen("example.txt", "r") or die("Unable to open file!");$content = fread($file, filesize("example.txt"));fclose($file);echo $content;?>? Explanation:
"r"= Open for reading onlyfilesize()= Gets file size to read full contentfclose()= Closes the file after reading
? 2. Read File Line-by-Line – fgets()
<?php$file = fopen("example.txt", "r") or die("Unable to open file!");while (!feof($file)) { echo fgets($file) . "<br>";}fclose($file);?>? Use Case:
Ideal for reading logs or large files line by line to save memory.
? 3. Quick Read – file_get_contents()
<?php$content = file_get_contents("example.txt");echo $content;?>? Simple and fast:
Reads entire file content into a string
No need to use
fopen()orfclose()
? 4. Read File into Array – file()
<?php$lines = file("example.txt");foreach ($lines as $line) { echo $line . "<br>";}?>? Use Case:
Returns each line of the file as an array element – good for line processing.
? Extra Tip: Check if File Exists
<?phpif (file_exists("example.txt")) { echo "The file exists.";} else { echo "File not found.";}?>? Security Note:
Always validate file names/paths and sanitize content before displaying or processing. Avoid reading user-uploaded files blindly.
Want an example where you read a text file submitted by a user or something like a simple log viewer?