Hi Austin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Read and Write File</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<div class="page">
<p class="nav"><a href="../../index.php">Home</a></p>
<?php
error_reporting(E_ALL); // set error reporting to all
ini_set('display_errors', 1); // show errors on the page
echo("<h1>Austin's Code for Read/Write File:</h1>");
$myFile = 'doc/notes.txt'; // doc folder is inside week10
// ---------- STEP 1: create the file if it does not exist ----------
if(file_exists($myFile))
{
echo('File found! <br>');
}
else
{
echo('File is NOT there -- creating a new file. <br>');
$handle = fopen($myFile, 'w') or die('Could not create file.');
fwrite($handle, 'This is my new file.');
fclose($handle);
}
// ---------- STEP 2: if the form was submitted, WRITE to the file ----------
if(isset($_POST['save']))
{
$newText = $_POST['fileContents'];
$handle = fopen($myFile, 'w'); // 'w' erases the old content first
if($handle)
{
echo('File is writeable -- writing the file. <br>');
fwrite($handle, $newText);
fclose($handle);
echo('<strong>Saved!</strong> <br>');
}
else
{
echo("Cannot write to the $myFile <br>");
}
}
// ---------- STEP 3: READ the file ----------
$content = '';
$handle = fopen($myFile, 'r');
if($handle)
{
echo('File is readable -- reading the file. <br><br>');
$size = filesize($myFile);
$content = ($size > 0) ? fread($handle, $size) : ''; // avoid fread length 0
fclose($handle);
echo('<h3>Current contents:</h3>');
echo('<p>' . nl2br(htmlspecialchars($content)) . '</p>');
}
else
{
echo("Cannot read the $myFile <br>");
}
?>
<!-- ---------- Form to edit and save ---------- -->
<h3>Edit the file:</h3>
<form action="" method="post">
<textarea name="fileContents" rows="8" cols="60"><?php echo htmlspecialchars($content); ?></textarea>
<br>
<input type="submit" name="save" value="Save File">
</form>
<hr>
<h2>Code follows</h2>
<div class="code"><?php highlight_file(__FILE__); ?></div>
<p class="nav nav-foot"><a href="../../index.php">Home</a></p>
</div>
</body>
</html>