CODE FOLLOWS
<?php
include('includes/header.php');
// Define the file path
$file = 'text.txt';
// 1. WRITE OPERATION
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST['comment'])) {
$userComment = htmlspecialchars($_POST['comment']) . PHP_EOL;
// FILE_APPEND keeps previous content; LOCK_EX prevents concurrent writes
file_put_contents($file, $userComment, FILE_APPEND | LOCK_EX);
}
// 2. READ OPERATION
$fileContent = "";
if (file_exists($file)) {
// Read the file into a string
$fileContent = file_get_contents($file);
} else {
$fileContent = "The file 'text.txt' was not found. Please create it!";
}
include('includes/footer.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tony's File </title>
</head>
<body>
<h2>Tony's Read/Write File </h2>
<form method="post" action="">
<label for="comment">Leave a comment:</label><br>
<input type="text" name="comment" id="comment" required>
<input type="submit" value="Save to File">
</form>
<hr>
<h3>Contents of text.txt:</h3>
<div style="background: #f4f4f4; padding: 10px; border: 1px solid #ccc;">
<?php
// nl2br converts newlines in the text file to HTML <br> tags
echo nl2br($fileContent);
?>
</div>
</body>
</html>
Tony's Read/Write File
Contents of text.txt:
aaaa
xxxx
xxxx