Tedd's Files Example - Christmas Card
Writing message to the docs/x-card.txt file.File is present and is readable
Reading docs/x-card.txt
Current:
2024/12/22Merry Christmas !
There are only 3 days until Christmas!
Happy Holidays!
From:
<?php
include('../includes/header4.php');
// code
error_reporting(E_ALL); // set error reporting to all
echo('<h1>Tedd\'s Files Example - Christmas Card</h1>');
// Note: the variables are being passed via POST ternary operators.
$name = isset($_POST['name']) ? $_POST['name'] : '';
$from = isset($_POST['from']) ? $_POST['from'] : '';
$str = "";
// scrub input from the form that will be printed (echoed) to the Browser.
$name = htmlspecialchars($name);
$from = htmlspecialchars($from);
// start X-MAS Message
$daysuntilxmas = ceil((mktime(0, 0, 0, 12, 25, date('Y')) - time()) / 86400);
$r = '<br>';
$str = date("Y/m/d") . $r . "Merry Christmas $name" . '!' . $r;
$str .= "There are only " . $daysuntilxmas . " days until Christmas! $r";
$str .= "Happy Holidays! $r";
$str .= "From: " . $from . "$r";
$file = 'docs/x-card.txt';
$handle = fopen($file, 'w');
// try writing the file
if ($handle) // if the resource is true then write to the file
{
echo("Writing message to the $file file. <br>");
// writes the message to the file
fwrite($handle, $str);
fclose($handle);
}
else // if the resource is not there, then create a file and write to it
{
echo("File is NOT there!<br>");
echo("Creating a new $file file. <br>");
echo("Writing to the new $file file. <br>");
// create a new file
$handle = fopen($file, 'w') or die('Could not create file.');
fwrite($handle, $str);
fclose($handle);
}
// read the file back in
if (file_exists($file)) // does file exist?
{
$handle = fopen($file, 'r'); // try reading the file
if ($handle)
{
echo("File is present and is readable <br> Reading $file <br>");
// read the contents of file into $str
$str = fread($handle, filesize($file));
fclose($handle);
}
else
{
echo("Cannot read the $file file! <br>");
}
}
echo('<hr>');
echo('<h3>Current:<br></h3>');
echo($str);
echo('<hr>');
echo('<h3>Fill in the Fields to Create your Early Christmas Card!</h3>');
?>
<form action="" method="POST">
<label for="name">To: </label>
<input type="text" id="name" name="name"><br>
<label for="from">From: </label>
<input type="text" id="from" name="from"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
include('../includes/footer4.php');
?>
Last modified: November 10 2022
Line Count: 93