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 20: Modify Existing File Content

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

Aim

To modify the content of an existing file — replacing a word and appending a new line — and display the file before and after the change.

Theory

The workhorse pattern is read–modify–write: load the file into a string with file_get_contents(), transform the string in PHP (str_replace(), preg_replace(), concatenation), then write the whole thing back with file_put_contents(). The final write truncates and replaces the file, so the on-disk result is always one complete, consistent new version — simple and reliable for the small files typical of web work.

Two narrower alternatives exist. For appending only, no read is needed: file_put_contents($path, $extra, FILE_APPEND) (or fopen() in mode a) adds to the end without touching what is already there. For in-place patching, fopen($path, "r+") opens read and write with the pointer at byte 0 — but fwrite() then overwrites bytes where the pointer sits rather than inserting, so replacing easy (4 characters) with powerful (8 characters) would smear over the text that follows. That is exactly why arbitrary edits use read–modify–write instead.

Finally, files are shared state: two requests running this cycle at the same time can interleave and silently lose one writer's changes. flock($handle, LOCK_EX) takes an exclusive advisory lock around the critical section (LOCK_SH for concurrent readers) — the standard defence once real traffic is involved.

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 p20_modify_file.php in C:\xampp\htdocs\wbplab.
  3. Open http://localhost/wbplab/p20_modify_file.php, or run php p20_modify_file.php — the script seeds its own demo file first.
  4. Compare the Before and After blocks in the output; re-run and note that only the appended timestamp changes, because the seeding line rewrites the original text at the start of every run.

Explanation of the Code

  • The first file_put_contents() seeds wbp_modify_demo.txt in the temp directory with PHP is easy. and a second line — guaranteeing "an existing file" and a deterministic starting state.
  • The Before modification: block prints the untouched content straight from disk.
  • Read: $content = file_get_contents($filePath) pulls the file into a string. Modify: str_replace("easy", "powerful", $content) returns a new string with the word swapped (it does not touch the file), and .= appends \nAppended line at plus date("H:i:s"). Write: file_put_contents($filePath, $content) truncates the file and writes the full modified text back.
  • The After modification: block deliberately calls file_get_contents() again — re-reading from disk proves the change was persisted, not merely held in the $content variable.

Expected Output

Before modification: followed by PHP is easy. and This line will be updated.; then After modification: followed by PHP is powerful., This line will be updated. and Appended line at <current time>, e.g. Appended line at 14:32:07. The replaced word and the freshly stamped time are the only differences between the two blocks.

🎯 Viva Questions

  1. Describe the read–modify–write cycle. Read the whole file into a string, transform the string in PHP, write the complete result back — the file always ends up as one consistent new version.
  2. How is text appended without reading the file first? file_put_contents($path, $data, FILE_APPEND) or fopen() in mode a — both write at the end and preserve existing content.
  3. What does mode "r+" do, and why is it risky for edits? It opens for reading and writing with the pointer at the start; fwrite() overwrites bytes in place, so writing text of a different length corrupts what follows.
  4. Does str_replace() change the file? No — it returns a new string; the file changes only when file_put_contents() writes that string back to disk.
  5. Why does the script re-read the file for the "after" display? Echoing $content would only show memory; re-reading from disk verifies that the write actually persisted.
  6. How are concurrent modifications to the same file made safe? Take an exclusive lock with flock($handle, LOCK_EX) around the read–modify–write section so writers serialise.

CO Mapping

CO1, CO2