Hello,
I have a voting php script that should work like this:
- the user clicks to vote
- if it is the first time, the script sends a cookie to the user. The cookie value is a ramdomly generated 10 digit user number.
- This number is also written in a mysql table.
- when the user tries to vote again, the script checks the cookie value against the number in the database. If the number exists, voting is allowed.
I use the following code to validate the cookie value. I thought it would prevent cookie tampering, by limiting the cookie value length to 10 digits and by allowing only numbers. However, someone has been able to voting by entering any kind of numbers, even 20 digit numbers! I dont know how he is doing this, it seems he is able to pass the validation, writing directly into the database, but I am not sure. Could anybody help me please?
/ when the user tries to vote for the first time, this creates the cookie:/
$usernumber=mt_rand(1000000000,9999999999);
setcookie($cookiename,$usernumber,time()+31536000);
/ the $usernumber is also written into the database /
/ Then, when the user comes back later to vote, this script gets the cookie value and validates it. /
$value=$_COOKIE['cookiename'];
$valuetrim=trim($value); // TRIM SPACES
$value=substr($valuetrim, 0, 10); / THIS LIMITS THE COOKIE VALUE LENGTH TO 10 DIGITS /
$numberofcharacters=strlen($value); / GETS THE NUMBER OF CARACTERS FROM COOKIE VALUE /
$i=0;
while ($i < $numberofcharacters)
{
$eachcharacter=substr($value,$i,1); / THIS GETS EACH CHARACTER FROM COOKIE VALUE STRING /
switch ($eachcharacter) { / CHECKS EACH CHARACTER /
case "1" : $validcookie=1;
break;
case "2" : $validcookie=1;
break;
case "3" : $validcookie=1;
break;
case "4" : $validcookie=1;
break;
case "5" : $validcookie=1;
break;
case "6" : $validcookie=1;
break;
case "7" : $validcookie=1;
break;
case "8" : $validcookie=1;
break;
case "9" : $validcookie=1;
break;
case "0" : $validcookie=1;
break;
default : $validcookie=0;
$i=$numberofcharacters; // THIS KILLS THE LOOP IF THERE IS ANY INVALID CHARACTER
break;
}
++$i;
}
if ($numberofcharacters!=10) / IF COOKIE VALUE LENGTH IS NOT 10, COOKIE IS INVALID/
{
$validcookie=0;
}
if ($validcookie==1)
{ // VOTING IS ALLOWED. VOTE IS WRITTEN IN THE DATABASE }
if ($validcookie==0)
{ // VOTING NOT ALLOWED}
/ After this validation, I check the cookie $value against the number stored previously in the MySql database. If there is a match, voting is allowed. /
/* By the way, there are only 5 form fields in the site, and I validated all of them in the same way I did with the cookie validation above. For example, there is a Name form field where I allowed only letters, and a phone number field where I allowed only numbers and ( ) -, and so on.
Thanks a lot for any help.
Marcelo
*/