-1

I am very new to PHP (currently doing a university project). My website is an admin site, with about 3 admin users who can log in and change the site etc. Currently, I have a delete function on my comments (comments which users can post to the site) but anybody who comes onto the site can see the delete function and can delete anybodies comments?

I want it so that only my admin's when logged in, can see the delete function, and subsequently be the only ones who can delete the comments. I have a users database with name, password, username and email columns. I was wondering if somebody could please take a look at my code and tell me how I can change this so that only when admins log in they can see the button and delete the comments.

  $str_message = "";
    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
    }else{

        //if ($_SESSION['admin'] == 'yes') {


        if(isset($_GET['delete'])){
            $deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";

            $deleter=mysqli_query($db_server, $deleteq);
            IF($deleter){
                echo"<p>That message was deleted!</p>";}}


        //}

        //Test whether form has been submitted 
        if(trim($_POST['submit']) == "Submit"){
            //Handle submission
            $resp = recaptcha_check_answer ($privatekey,
                                            $_SERVER["REMOTE_ADDR"],
                                            $_POST["recaptcha_challenge_field"],
                                            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
                // What happens when the CAPTCHA was entered incorrectly
                $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it    
    again. 
                                (reCAPTCHA said: " . $resp->error . ")";
            } else {

                // Your code here to handle a successful verification
               $comment = $_POST['comment'];
                if($comment != ""){
                    $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                    mysqli_query($db_server, $query) or die("Comment insert failed: " .     
     mysqli_error($db_server) );
                    $str_message = "Thanks for your comment!";
                }else{
                    $str_message = "Invalid form submission";
                }
            }
        }
        //Create page with or without submission 
        $query = "SELECT * FROM comments";
        $result = mysqli_query($db_server, $query);
        if (!$result) die("Database access failed: " . mysqli_error($db_server) );
        {

        while($row = mysqli_fetch_array($result)){ 
        $ID= $row['ID'];



            $str_result .=  "<p><em>Comment $j (" . $row['commDate'] . 
                    ")</em><br /> " .$row['comment'] . "</p>
                    <a href ='commentnow.php?delete=$ID
                    '>Delete</a><hr />"; 
        }
        mysqli_free_result($result);
    } } 

     ?>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Unrelated but I am fairly sure it's common practice to not delete data but instead just have a deleted flag. I would suggest considering this approach. –  Jan 10 '14 at 21:09
  • Uncomment the code that checks whether the user is an admin before performing the deletion. – Barmar Jan 10 '14 at 21:10
  • ^ and then at the bottom also add an if statement to have two possible `$str_result` assign statements depending on if the user is an admin or not (if the user is admin obviously don't have the delete button) –  Jan 10 '14 at 21:13

3 Answers3

1

If we assume that your commented out statement to check if the user is an admin (if ($_SESSION['admin'] == 'yes')) works, then the following code should give you a good idea of how to do it. There are two places where you need to add the if statement. I haven't been able to test this but look in this code for where you see // ADMIN IF STATEMENT and I hope you understand what changes to your code need to be made for it to work properly.

<?

$str_message = "";

if (!$db_server) {

    die("Unable to connect to MySQL: " . mysqli_connect_error());

} else {

    if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT

        if (isset($_GET['delete'])) {

            $deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
            $deleter = mysqli_query($db_server, $deleteq);

            if ($deleter) {

                echo "<p>That message was deleted!</p>";

            }

        }

    }

    //Test whether form has been submitted 
    if (trim($_POST['submit']) == "Submit") {

        //Handle submission
        $resp = recaptcha_check_answer(
            $privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]
        );

        if (!$resp->is_valid) {

            // What happens when the CAPTCHA was entered incorrectly
            $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")";

        } else {

            // Your code here to handle a successful verification
            $comment = $_POST['comment'];

            if ($comment != "") {

                $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                mysqli_query($db_server, $query) or die("Comment insert failed: " . mysqli_error($db_server) );
                $str_message = "Thanks for your comment!";

            } else {

                $str_message = "Invalid form submission";

            }

        }
    }

    //Create page with or without submission 
    $query = "SELECT * FROM comments";
    $result = mysqli_query($db_server, $query);

    if (!$result) die("Database access failed: " . mysqli_error($db_server) ); {

        while ($row = mysqli_fetch_array($result)) { 

            $ID = $row['ID'];

            if ($_SESSION['admin'] == 'yes') { // ADMIN IF STATEMENT

                $str_result .=  "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p><a href ='commentnow.php?delete=$ID'>Delete</a><hr />"; 

            } else {

                $str_result .=  "<p><em>Comment $j (" . $row['commDate'] . ")</em><br /> " .$row['comment'] . "</p>"; 

            }
        }

        mysqli_free_result($result);

    }

} 

?>
  • `$deleteq = "DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";` I think this query is vulnerable to sql injections. also see http://stackoverflow.com/questions/5370426/how-does-affect-a-mysql-query-in-php – Roman Pickl Jan 10 '14 at 21:47
  • @RomanPickl a lot of the posters code is wrong but I personally don't like to grill people on vulnerabilities –  Jan 10 '14 at 21:50
  • @Sinmai I understand that. Sometimes parts of the code seems to be beyond fixing without changing a lot of it, probably dampering the interest of a learning coder. however it is good to point such things out anyway I guess. – Roman Pickl Jan 11 '14 at 08:08
0
if ($_SESSION['admin'] == 'yes') {
<insert code to generate a delete button here>
}
donsiuch
  • 343
  • 3
  • 8
  • 18
0

First you need to change in your log in page. When an user login then check if he is an admin user. if yes the set a session variable ($_SESSION['admin']) to yes or set it to no. try like this:

//login.php
if (!$db_server){
            die("Unable to connect to MySQL: " . mysqli_connect_error());
        }else{

     session_start(); 
     $sql="Select * FROM users WHERE user_name = 'your_username' and LIMIT 1";
     $result=mysqli_query($db_server, $sql);
     $objUser = $result->fetch_object();
     if($objUser->user_type =="admin")
        $_SESSION['admin'] = 'yes';
      else
       $_SESSION['admin'] = 'no';
  //rest of your code for login the user
}

Then in your delete page check if current user is admin or not. If yes then execute query else echo a message. like this:

session_start(); 
$str_message = "";
    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
    }else{


        if(isset($_GET['delete'])){
            if ($_SESSION['admin'] == 'yes') {
              $deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";

              $deleter=mysqli_query($db_server, $deleteq);
               if($deleter){
                echo"<p>That message was deleted!</p>";}
            }
          else
           {
            echo "you are not admin";
           }

        }

        //Test whether form has been submitted 
        if(trim($_POST['submit']) == "Submit"){
            //Handle submission
            $resp = recaptcha_check_answer ($privatekey,
                                            $_SERVER["REMOTE_ADDR"],
                                            $_POST["recaptcha_challenge_field"],
                                            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
                // What happens when the CAPTCHA was entered incorrectly
                $str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it    
    again. 
                                (reCAPTCHA said: " . $resp->error . ")";
            } else {

                // Your code here to handle a successful verification
               $comment = $_POST['comment'];
                if($comment != ""){
                    $query = "INSERT INTO comments (comment) VALUES ('$comment')";
                    mysqli_query($db_server, $query) or die("Comment insert failed: " .     
     mysqli_error($db_server) );
                    $str_message = "Thanks for your comment!";
                }else{
                    $str_message = "Invalid form submission";
                }
            }
        }
        //Create page with or without submission 
        $query = "SELECT * FROM comments";
        $result = mysqli_query($db_server, $query);
        if (!$result) die("Database access failed: " . mysqli_error($db_server) );
        {

        while($row = mysqli_fetch_array($result)){ 
        $ID= $row['ID'];



            $str_result .=  "<p><em>Comment $j (" . $row['commDate'] . 
                    ")</em><br /> " .$row['comment'] . "</p>
                    <a href ='commentnow.php?delete=$ID
                    '>Delete</a><hr />"; 
        }
        mysqli_free_result($result);
    } } 

     ?>

I think it makes sense !

Awlad Liton
  • 9,366
  • 2
  • 27
  • 53