Mark D
Mark D

Reputation: 257

Creating a comment section for a PHP webpage

I am trying to create a commenting area for a php webpage.

I was following along this video (I only followed the code because I don't know the creator's language) and the code doesn't seem to work.

Here is the PHP bit of the code (modified), which is where the runtime errors are telling me there's something wrong. I commented the lines which give an error:

<?php
        $name = $_POST["name"];
        $email = $_POST["email"];
        $url = $_POST["url"];
        $message = $_POST["message"];
        $post = $_POST["post"];

        if($post){

        $write = fopen("../database/fnaticcomments.txt", "a+");
        fwrite($write, "<b>$name<br>$email<br>$url<br></b>$message<br> ");
        fclose($write);

        $read = fopen("../database/fnaticcomments.txt", "r+t");
        echo "All comments:";

        while(!feof($read)){
        echo fread($read, 1024);
        }
        fclose($read);
        }

        else{

        // $read = fopen("../database/fnaticcomments.txt", "r+t");
        echo "All comments:";

        // while(!feof($read)){
        // echo fread($read, 1024);
        }
        fclose($read);
        }
        ?>

If someone could help me it would be much appreciated.

*The errors I'm getting are:

(1)Warning: fopen(../database/fnaticcomments.txt) [function.fopen]: failed to open stream: Permission denied in /home/delpilam/public_html/firstProject/php/fnaticpage.php on line 95

(2)Warning: feof() expects parameter 1 to be resource, boolean given in /home/delpilam/public_html/firstProject/php/fnaticpage.php on line 98

(3)Warning: fread() expects parameter 1 to be resource, boolean given in /home/delpilam/public_html/firstProject/php/fnaticpage.php on line 99

Upvotes: 0

Views: 1061

Answers (1)

ankit.json
ankit.json

Reputation: 150

In else condition you are trying to read a file which does not exists if no comment is added, add a file_exists check

try this:

<?php
        $name = $_POST["name"];
        $email = $_POST["email"];
        $url = $_POST["url"];
        $message = $_POST["message"];
        $post = $_POST["post"];

        if($post){

        $write = fopen("../database/fnaticcomments.txt", "a+");
        fwrite($write, "<b>$name<br>$email<br>$url<br></b>$message<br> ");
        fclose($write);

        $read = fopen("../database/fnaticcomments.txt", "r+t");
        echo "All comments:";

        while(!feof($read)){
        echo fread($read, 1024);
        }
        fclose($read);
        }

        else{

         if(file_exists("../database/fnaticcomments.txt")) {

          $read = fopen("../database/fnaticcomments.txt", "r+t");
          echo "All comments:";

           while(!feof($read)){
            echo fread($read, 1024);
           }
           fclose($read);

         } else {
            echo "No comments";
         }

        }
        ?>

Upvotes: 2

Related Questions