security - COOKIE/PHP: Secure login for REAL

205

I hate to make ANOTHER cookie question. I have read a lot now and it confuses me..

I have seen a lot of How-To's and tutorials on YouTube and other site from people who called themselves professionals. But I can't get this straight. So I have to ask for some other folks opinions. Okey, cookies is HARD to make secure. But there is a few things you can do, right?

In many tutorials PHP programmers choose to store both username and password in a cookie. What I can understand that is a pretty stupid thing to do? Especially if you use this as the authentication on the site. Just ask if the cookie exist without check the database. But that isn't good enough either. If someone edit the cookie with another username. BAM, full access to that account.

So, I have been thinking. Is it a good way to create and store JUST a token as the cookie? When a user go to the site with this cookie-token. The site asks the database: "Which one of you losers owns this?". If it's a match and you're in. This token has to be unpredictable of course! For the human mind I mean. And pretty hard for a brute-force attack.

Take a look at this token:

$salt = 'S0M3TH1N6';

$identifier = md5($salt . md5($username . $salt));
$token = md5(uniqid(rand(), TRUE));
$timeout = time() + 60 * 60 * 24 * 7;

setcookie('auth', "$identifier:$token", $timeout);

When this cookie access, the site call the database to see if a user has this as token. If no hit, you'll be back to the login page. If there is a hit you can fetch and store everything else you need in a session instead. As I can understand sessions are much more trustable because they are on the server-side. Therefore, don't store username and password in a cookie. Because a cookie is on the client's side. And of course use mysql_real_escape_string(); on everything you fetch or add to the database.

What do you folks think about this? Maybe I have missed something, or a lot. Feel free to comment. :)

Thanks in advance.

262

Answer

Solution:

You should just use a session.

upon log in authentication set a session:

session_start();
//login succesful?? then:
$_session['user'] = array('fname'=>$query['fname'], 'lname'=>$query['lname']...;

then on each page:

    session_start();
    session_regenerate_id();

    if ($_SESSION['user']){
        echo '<pre>';
        echo $_SESSION['user']
        echo '</pre>';
   }

People are also looking for solutions to the problem: php - Applying a variable level array to an existing array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.