I’m trying to write a php script where it displays a text form and a submit button. The page then loads the contents of a text file.
When the user enters text into the form, and hit submit, I’d like it so that the text file has their entry added, and then the page reloads.
Something like this:
User types “Lorem ipsum” into the form, and presses submit.
The text file was empty, so it is updated to say “Lorem ipsum”
Another user, using the same form, types “KFC is tasty”, and presses submit.
The new data is added to the start of the text file, to make it now read “KFC is tasty
Lorem ipsum”
Here’s the code I have so far:
<?php
//builds the page
echo "<html>";
//makes a form for the user to input to
echo "<form action=\"action.php\" method=\"post\">";
echo "<p>Entry: <input type=\"text\" name=\"input\" /></p>";
echo "<p><input type=\"submit\" name=\"Shbmit\" /></p>";
echo "</form><br><br>";
//collapses the array (wtf? must read up on this) $_POST into a string.
$entry = implode("", $_POST);
//below is the read section of the script
$myFile = "text.txt";
//opens the file - reading
$fh = fopen($myFile, 'r');
$fileLength = filesize($myFile);
//gets the data from the text file, only if the file has contents
if( filesize($myFile)!=0)
{
$theData = fread($fh, filesize($myFile));
}
else
{ //if the file is blank, so is this var, ye.
$theData = "";
}
//closes the file - reading
fclose($fh);
//opens the file - writing
$fh = fopen($myFile, 'w');
//only attempts to write to the file if there's already an entry
if( strlen( $entry ) != 0 )
{
fwrite($fh, ( entry + "<br><br>" + $theData ) );
}
//closes the file - writing.
fclose($fh);
//outputs the data read from the file - or, nothing,
//if there wasn't anything in the file to begin with...
echo $theData;
//end of this file
?>
The error lies in execution: whenever the page is first loaded, it displays the original contents of the text file. When submit is clicked, however, the text file is made blank.
What am I doing wrong?