Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 19: Read and Display File Content

Lesson 26 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

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 $length bytes from the current pointer position, and fclose($handle) releases the handle. Passing filesize($path) as the length is the classic "read it all" idiom — same result as file_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

  1. Start Apache from the XAMPP Control Panel (or just open a terminal).
  2. Save the snippet as p19_read_file.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p19_read_file.php, or run php p19_read_file.php — the script writes its own sample file first, so no manual preparation is needed.
  4. 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() seeds wbp_read_demo.txt in 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 the Using 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

  1. file_get_contents() vs fread() — 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.
  2. Why is an fgets() loop preferred for very large files? It reads one line per call inside while (!feof($handle)), so memory use stays constant regardless of file size.
  3. What does the second argument of fread() specify? The maximum number of bytes to read from the pointer; passing filesize($path) there means "the whole file".
  4. 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.
  5. 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.
  6. 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