0

I have a php code that votes I want to prevent users from voting twice. I want to check if user if the user has voted, and prevent them from voting again. This is my code below:

<?php
  include('conn.php');
  $expire = 24*3600*30; //after one day
  setcookie('SnugglesVotingSystem'.$_POST['id'], 'voted', time() + $expire, '/');     // Place a cookie
  if($_POST) 
  {
    try{
    $query = "UPDATE tbl_images SET up =up".$_POST['value']." WHERE      id=".$_POST['id'].""; // Update number with +1 or -1
       // Prepare statement
    $stmt = $DB->prepare($query);
    // execute the query
    $stmt->execute();
    // echo a message to say the UPDATE succeeded
    echo $stmt->rowCount();
    }
    catch(PDOException $e)
    {
    echo $query . "<br>" . $e->getMessage();
    }
    $value = "SELECT up FROM tbl_images WHERE id=".$_POST['id'].""; // Get the new number value
    $stmt = $DB->prepare($value);
            $stmt->execute();
            $images = $stmt->fetchAll();
    if (is_array($value) && isset($_POST['up'])) {

    echo $value['up'];
}
    //echo $value['up']; // Send back the new number value
}
?>
vanderman
  • 1
  • 2
  • What is the problem ? – FrancoisBaveye Nov 05 '15 at 15:14
  • 2
    Lovely [sql injection attack](http://bobby-tables.com) vulnerability. Enjoy having your server pwn3d. – Marc B Nov 05 '15 at 15:14
  • 1
    Just a little pointer... you're not really using prepared statements correctly here. You still put the user input straight into your queries. – M. Eriksson Nov 05 '15 at 15:14
  • I think you need to determine how you want to limit them. Do you want to limit them by IP address ($_SERVER['REMOTE_ADDR']) and log it, maybe set a cookie value to say if they voted, not sure the security and accuracy levels you're going for. And the SQL Injection is a problem. – ckimbrell Nov 05 '15 at 15:20
  • A cookie can easily be removed (Firefox deletes all of them on each closing), so the users can vote several times. If the user can login with an email address for example, it's the more secure to identify one user on each connexion. – bdanos Nov 05 '15 at 15:21
  • I would suggest only member can vote so it is easier to control, and that SQL injection vulnerability.... – Andrew Nov 05 '15 at 15:25

1 Answers1

1

You need to save some sort of flag in your database to determine if this user has already voted for this image. Instead of keeping just a total number of votes for an image, insert a new record into a new image_votes table for each vote. The record would just contain user_id and image_id. Then, you can count any one user's votes or image's votes, and you can easily do a SELECT on this table to see if the user has already voted, and then notify them that they cant vote again or insert a row for them.

Mikel Bitson
  • 3,583
  • 1
  • 18
  • 23