Aim
To read a previously created file and display its content using PHP's file-reading functions.
Theory
PHP offers several reading strategies with different memory profiles:
file_get_contents($path)slurps the whole file into one string — the simplest option and the fastest for small files, but it holds the entire file in memory at once.- The handle API reads under manual control:
fopen($path, "r")opens read-only (failing if the file is missing),fread($handle, $length)returns up to$lengthbytes from the current pointer position, andfclose($handle)releases the handle. Passingfilesize($path)as the length is the classic "read it all" idiom — same result asfile_get_contents(), but with an explicit handle that could also seek (fseek()) or read in chunks. - For files too large to hold in memory, read incrementally:
while (!feof($handle)) { $line = fgets($handle); … }processes one line per iteration in constant memory — the right shape for logs. Related helpers:file()returns the file as an array of lines;readfile()streams a file straight to the output buffer.
One web-specific caution: file text is data, not markup. Before echoing file content into an HTML page it should pass through htmlspecialchars(), or any <script> stored in the file would execute in the visitor's browser.
Requirements
- XAMPP/WAMP with Apache and PHP 8.x, or the PHP CLI / an online PHP compiler
- Code editor (VS Code); browser or terminal
Procedure
- Start Apache from the XAMPP Control Panel (or just open a terminal).
- Save the snippet as
p19_read_file.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p19_read_file.php, or runphp p19_read_file.php— the script writes its own sample file first, so no manual preparation is needed. - Compare the two printed blocks: both show the same three lines, retrieved by two different mechanisms.
Explanation of the Code
- The opening
file_put_contents()seedswbp_read_demo.txtin the system temp directory with three\n-separated lines — standing in for "the previously created file" (Practical 17) so the demo is self-contained. - Method 1:
file_get_contents($filePath)returns the complete text in one call, echoed under theUsing file_get_contents():heading. - Method 2:
fopen($filePath, "r")obtains a read-only handle;fread($handle, filesize($filePath))asks for exactly as many bytes as the file holds, so a single call drains it;fclose($handle)then releases the handle. - Both methods print identical text — the point of the practical is the mechanism: one-shot convenience versus explicit handle control.
Expected Output
Two labelled blocks with the same content: Using file_get_contents(): followed by First line, Second line, Third line, then a blank line, then Using fopen()/fread(): followed by the same three lines again. In a browser the lines appear run together (newlines are not <br> tags) unless the page source is viewed; in a terminal they print exactly as listed.
🎯 Viva Questions
file_get_contents()vsfread()— when does each fit?file_get_contents()for one-shot reads of small files;fread()when a handle is needed for chunked reads, seeking or locking.- Why is an
fgets()loop preferred for very large files? It reads one line per call insidewhile (!feof($handle)), so memory use stays constant regardless of file size. - What does the second argument of
fread()specify? The maximum number of bytes to read from the pointer; passingfilesize($path)there means "the whole file". - What does
fopen()with mode"r"require and set up? The file must already exist; it opens read-only with the pointer at byte 0. - Why call
fclose()when the script ends anyway? It promptly frees the handle and any lock; relying on script shutdown is sloppy in long-running or looping code. - Why wrap file content in
htmlspecialchars()before echoing it on a web page? The file may contain markup; escaping turns it into visible text instead of executable HTML/JavaScript (XSS defence).
CO Mapping
CO1, CO2