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
- Start Apache from the XAMPP Control Panel (or just open a terminal).
- Save the snippet as
p20_modify_file.phpinC:\xampp\htdocs\wbplab. - Open
http://localhost/wbplab/p20_modify_file.php, or runphp p20_modify_file.php— the script seeds its own demo file first. - 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()seedswbp_modify_demo.txtin the temp directory withPHP 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 atplusdate("H:i:s"). Write:file_put_contents($filePath, $content)truncates the file and writes the full modified text back. - The
After modification:block deliberately callsfile_get_contents()again — re-reading from disk proves the change was persisted, not merely held in the$contentvariable.
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
- 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.
- How is text appended without reading the file first?
file_put_contents($path, $data, FILE_APPEND)orfopen()in modea— both write at the end and preserve existing content. - 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. - Does
str_replace()change the file? No — it returns a new string; the file changes only whenfile_put_contents()writes that string back to disk. - Why does the script re-read the file for the "after" display? Echoing
$contentwould only show memory; re-reading from disk verifies that the write actually persisted. - 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