Ruble Gomes
Ruble Gomes

Reputation: 117

Cookie security php

I'm using a basic cookie system for the "remember me" part of a log in form. Here is the code:

    if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];

    if($username&&$password)
    {
        $connect = mysql_connect('localhost','root','');
        mysql_select_db('phplogin');
        $query = mysql_query("SELECT * FROM utilisateurs WHERE NomUtilisateur='$username' AND MotDePasse='$password'");

        $rows = mysql_num_rows($query);
        if($rows==1)
        {
            if($_POST['checkbox'])
            {
                setcookie('username',$username,time()+3600);
                header('Location: membre.php');     

            }else{$_SESSION['username']=$username;header('Location:membre.php');}
        }else echo "Something something error";
    }else echo "Something something darkside";
}

I'm not quit sure if I need to secure the cookie and if yes, how to do it? All I really want to do is not allowing people to log in in another user account with a fake cookie or put sensitive information on the clear in the cookie.

Upvotes: 0

Views: 342

Answers (1)

Sibu
Sibu

Reputation: 4617

Currently anybody can log himself if he knows the username of a user. Even if a cookie is set you need to have a process to identify users that they are genuine clients..like for ex., when a user logs in you can save a random alphanumeric string saved in the cookies and your DB against that user, and the next time you cross check the string with the value in your DB and remember to change the alphanumeric string after every X days, this prevents attackers from copying someone’s cookies and using them to login. Something like this do

$uniquekey     = 'A234W';
$randomstring  = sha1(strval(rand(0,microtime(true))+ $uniquekey + strval(microtime(true))));
setcookie( 'loginID', $randomstring, time()+60*60*24*7,'/', 'www.yoursite.com', false, true);  

and when reading from cookie use mysql_real_escape_string to filter any malicious code

Upvotes: 1

Related Questions