Kaylyn's $_POST Read/Write File Example
File is there and readable -- reading the mytext file.
<?php
include('includes/header.php');
error_reporting(E_ALL);
echo('<h1>Kaylyn\'s $_POST Read/Write File Example</h1>');
$step = isset($_POST['step']) ? $_POST['step'] : 0;
$str = isset($_POST['message']) ? $_POST['message'] : '';
$str = htmlspecialchars($str);
echo($str);
echo('<br>');
$file='text3.txt';
if ($step == 1)
{
$handle = fopen($file, 'w'); // try writing the file
if ($handle)
{
echo('Writing message to the text3 file. <br>');
// writes the message to the text3 file
fwrite($handle, $str);
fclose($handle);
}
else
{
echo('Cannot write to the text3 file! <br>');
}
}
if (file_exists($file)) // does file exist?
{
$handle = fopen($file, 'r'); // try reading the file
if ($handle)
{
echo('File is there and readable -- reading the mytext file. <br>');
// read the contents of the mytext file and place in $str
$str = fread($handle, filesize($file));
// scrub $str
$str = htmlspecialchars($str);
fclose($handle);
}
else
{
echo("Cannot read the mytext file! <br>");
}
}
else
{
echo('File is NOT there -- creating a new mytext file. <br>');
// create a new mytext file
$handle = fopen($file, 'w') or die('Could not create file.');
fwrite($handle, '');
fclose($handle);
}
// $str = nl2br($str);
?>
<br><br>
<form action="" method="POST">
<label for="message">Message</label>
<textarea id="message" name="message" rows="4" cols="50">
<?php echo($str); ?>
</textarea>
<br><br>
<input type="hidden" name="step" value="1">
<input type="submit" name="submit" value="Submit">
</form>
<?php
include('includes/footer.php');
?>