Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP comment box using a txt file

I need to make a comment box using a txt file or anything else that can be queried passively, without using a database server. As I'm fairly new to PHP programming the first idea was to use a text file. The code in general to accomplish this, as far as I can think of logically would be :

    <html>
<head></head>
<body>
<form method = "post">
<textarea name = "txt" cols = "25" rows = "5">
Place your comment here ...
</textarea><br><br>
<input type = "submit" value = "Submit" onclick = "<?php
    $com = $_POST["txt"];
    $file = fopen("inrg.txt", "a");
    fwrite($file, "<br>");
    for($i=0; $i <= strlen($com) - 1; $i++)
        {
        fwrite($file, $com[$i]);
        if($i % 37 == 0 && $i != 0)
            fwrite($file, "<br/>");
        }
    fwrite($file, "<br>------------------------------------------");
    fclose($file);
?>">
<br>
</form>
<font face = "Times New Roman"><b><p>Textul introdus este: </p></b></font>
<font face = "Comic Sans MS" color = "red" size = "2" >
<?php
$file = fopen("inrg.txt", "r");
echo fread($file, filesize("inrg.txt"));
fclose($file);
?>
</font>
</body>
</html>

Nothing fancy yet, and it does needs some improvements on the esthetics side. The thing is after I submit something in the comment box, it shows properly but if I do reload in the web browser, the last posted comment it's posted again as many times as I reload the page. Also if there's a way with PHP to make the initial "Place your comment here ..." disappear


1 Answers

    <!doctype html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Example document</title>
      </head>
      <body>
<?php
// the relative path to the file
$fname = "theFile.txt";
// read in the file if present
if(file_exists($fname)) $txt = file_get_contents($fname);

// if the user pushes the submit button
if(isset($_POST["txt"])){
    $txt = $_POST["txt"];   // get the entered content
    file_put_contents($fname,$txt);    // write the content to the file
}
?>
<form method="post" action="#">
<textarea name = "txt" cols = "25" rows = "5">
<?php echo $txt; ?>
</textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
      </body>
    </html>

The folder where the script resides must be writable by PHP (=WebServer). This script is critical, no security against cross side scripting hacks. There might be problems concerning line breaks.

like image 127
joergy Avatar answered Aug 14 '26 15:08

joergy