Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping people from hijacking a voting system using PHP?

Tags:

php

What are some code examples that I can use to stop people from casting votes to give them a higher rating by hacking the php script?

like image 444
BaRt Avatar asked Jan 29 '10 23:01

BaRt


2 Answers

The first line of defense is a cookie.

Basically, you set the cookie on their machine, and disable voting if it is present.

setcookie('cookiename', 'voted=1');

// and later

if(isset($_COOKIE['cookiename']) && $_COOKIE['cookiename'] = "voted=1")
{
     // error
}

This gets rid of a database call you might need to make in order to validate their voting. It is a good idea to keep this in place, because it is like caching: the fewers hits to the database the better.

The second line of defense is IP limiting. You basically would check for a IP address log in your database, and see if they voted recently.

mysql_query('INSERT INTO TABLE (`IP_ADDR`, `TIME`) VALUES("'.$_SERVER['REMOTE_ADDR'].'", "'.time().'")');

// and later

$results = mysql_query('SELECT IP_ADDR FROM TABLE WHERE IP_ADDR="'.$_SERVER['REMOTE_ADDR'].'"');

if(mysql_num_rows($results) != 0)
{
    // error
}

Turning your entire script into something along the lines of

if(isset($_COOKIE['cookiename']) && $_COOKIE['cookiename'] = "voted=1")
{
     die("You have voted recently.");
}

$results = mysql_query('SELECT IP_ADDR FROM TABLE WHERE IP_ADDR="'.$_SERVER['REMOTE_ADDR'].'"');

if(mysql_num_rows($results) != 0)
{
    die("You have voted recently");
}

//Do Voting Stuff Here
vote($_GET['vote']);

// Record the vote.
setcookie('cookiename', 'voted=1');
mysql_query('INSERT INTO TABLE (`IP_ADDR`, `TIME`) VALUES("'.$_SERVER['REMOTE_ADDR'].'", "'.time().'")');

You'll also have to add in the expiration times and such, but the basic jist of it is there.

like image 174
Tyler Carter Avatar answered Oct 12 '22 03:10

Tyler Carter


  1. Set cookies to already voted users and disallow to vote for some time.

  2. Beside cookies protection add ip address protection. Single ip address can vote only one time per some period of time. Good alternative for ip protection is protection by combined scheme (ip+user_agent+...).

  3. Ask users to enter captcha when they're doing actions too fast.

like image 21
Kirzilla Avatar answered Oct 12 '22 04:10

Kirzilla