Veronica's Reader-Writer:

This script finds/creates and reads/writes a file

Looking for file...
File found!

Checking for readability...
File is readable -- reading the file.
Click refresh on your browser to see what the file, read_write.txt, says.

Checking for writeability...
File is writeable -- writing the file.
Writing~ ~to the file.




 

CODE FOLLOWS

<?php
include('includes/header.php');

// set error reporting to all
error_reporting(E_ALL);

// variable being passed via POST ternary operator
$str_write = isset($_POST['message']) ? $_POST['message'] : '';

// scrub input
$str_write htmlspecialchars($str_write);

echo(
"<h1>Veronica's Reader-Writer:</h1>");

echo(
'<h2>This script finds/creates and reads/writes a file</h2>');

$myFile 'read_write.txt';

// if file does not exist, create one
echo('Looking for file... <br>');
if(
file_exists($myFile))
{
    echo(
'File found! <br>');
}
else
{
    echo(
'File is NOT there -- creating a new file. <br>');

    
// create a new file
    
$handle fopen($myFile'w') or die('Could not create file.');
    
fwrite($handle'');
    
fclose($handle);
}
echo(
'<br>Checking for readability... <br>');

// try reading the file
$handle fopen($myFile'r');
if(
$handle)
{
    echo(
'File is readable -- reading the file. <br>');

    
// verify the filesize
    
if (filesize($myFile))
    {
        
// read the contents of the file
        
$str_read fread($handle,  filesize($myFile));
        
fclose($handle);
        
// add new line breaks
        
$str_read nl2br($str_read);
        echo(
"File reads: $str_read<br>");
    } else
    {
        echo(
"Click refresh on your browser to see what the file, $myFile,  says. <br>");
    }

}
else
{
    echo(
"Cannot read the $myFile ! <br>");
}
echo(
'<br>Checking for writeability... <br>');

// try writing the file
$handle fopen($myFile'w');
if(
$handle)
{
    echo(
'File is writeable -- writing the file. <br>');

    
// write the new value from the input to the file
    
fwrite($handle$str_write);
    
fclose($handle);
    echo(
"Writing~ $str_write ~to the file.<br>");
}
else
{
    echo(
"Cannot write to the $myFile !");
}

?>

<br><br>
<form action="" method="POST">
    <label for="message">Message</label>
    <textarea id="message" name="message" rows="4" cols="50"><?php echo($str_write); ?>
        </textarea>
    <br><br>
    <input type="submit" name="submit" value="Submit">
</form>
<?php

include('includes/footer.php');
?>