<?php
include('includes/header.php');
// code
error_reporting(E_ALL); // set error reporting to all
echo "<h1>Ka Yee's Read and Write file Form</h1>";
$file = '../docs/mytext.txt';
$step = isset($_POST['step']) ? (int)$_POST['step'] : 0;
$str = isset($_POST['message']) ? $_POST['message'] : '';
$isSubmitted = false;
// Handle write routine
if ($step === 1 && isset($_POST['action']) && $_POST['action'] === 'write') {
@mkdir(dirname($file), 0755, true);
file_put_contents($file, $str);
$isSubmitted = true;
}
// Read existing file content
echo "<h2>File is readable -- reading the mytext file.</h2>";
$str = file_exists($file) ? file_get_contents($file) : '';
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" method="POST">
<textarea name="message" rows="4" cols="50"><?php echo htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); ?></textarea>
<input type="hidden" name="step" value="1">
<button type="submit" name="action" value="write">Submit</button>
</form>
<?php
// Display the file contents automatically after clicking Submit
if ($isSubmitted) {
echo "<h3>File Contents:</h3>";
if (file_exists($file)) {
echo "<p>" . nl2br(htmlspecialchars($str, ENT_QUOTES, 'UTF-8')) . "</p>";
} else {
echo "<p><em>File does not exist yet.</em></p>";
}
}
include('includes/footer.php');
?>