Problem with text file and PHP

1

Text and PHP files: How do I automatically display the message I just sent via POST on the same page?

here is my code:

<html>

<head>
<title>mboard</title>
</head>

<body>

<?php

$myfile = fopen("mboard.txt", "a+") or die("Unable to open file!");

if (filesize("mboard.txt") > 0) {
echo fread($myfile,filesize("mboard.txt"));
} else { 
echo "empty file!";
}

if (!empty($_POST)) {

$txt= $_POST["text-mboard"];

fwrite($myfile, $txt);

echo fread($myfile,filesize("mboard.txt"));

};

if ($_POST) {
echo fread($myfile,filesize("mboard.txt"));
};

?> 

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="text-mboard">
</form>

<?php fclose($myfile); ?>

</body>

</html>
    
asked by María Gregorio 06.07.2017 в 17:34
source

1 answer

2

Personally I think that using fread and fwrite is killing flies with cannon fire, since it is for reading binary files.

On the other hand, you had two frees, whether they sent you something or not, that I deleted.

<?php

$filename = "mboard.txt";

$myfile = file_get_contents($filename) or die("Unable to open file!");

if ( $myfile == '' ) {
   echo "empty file!";
}

if (!empty($_POST)) {

   $txt= $_POST["text-mboard"];

   file_put_contents($filename, $txt, FILE_APPEND);

   echo file_get_contents($filename);

};
?> 

<form method="post" action="<?=$_SERVER['PHP_SELF']; ?>">
   <input type="text" name="text-mboard">
</form>

</body>

</html>
    
answered by 06.07.2017 / 19:02
source