Php – Stopping people from hijacking a voting system using PHP

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?

Best Solution

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.