1

I want to implement a "remember me" function in my site with PHP.

My thought is to store the username and hashed password string in cookies. But anybody can still get the cookie's value and set the cookie from another computer (using the browser's debug console) to reload the page and log in, right? How to prevent this?

Braiam
  • 1
  • 11
  • 50
  • 74
kevinHuang
  • 155
  • 2
  • 7

2 Answers2

0

Here is code to prevent it:

Create Cookie:

    $customer_id = 1;
    $client_ip = '127.0.0.1';
    $tokenSave = ['code'=>string_encrypt($customer_id.'+'.$client_ip.'+'.$_SERVER['HTTP_USER_AGENT']),'created'=>date('Y-m-d H:i:s')];
   setcookie(
         'loggedIn',
         serialize($tokenSave),
         time() + (10 * 365 * 24 * 60 * 60)
  ); 

Verify LoggedIn Cookie

$loggedIn = isset($_COOKIE['loggedIn'])?unserialize($_COOKIE['loggedIn'], ["allowed_classes" => false]):NULL;
        if(!empty($loggedIn)){
            $decypted = string_decrypt($loggedIn['code']);
            $realInfo = explode('+', $decypted);
            $savedId = $realInfo[0];
            $savedIp = $realInfo[1];
            $savedUserAgent = $realInfo[2];
            if($_SERVER['HTTP_USER_AGENT'] != $savedUserAgent && $savedIp != $this->get_client_ip()){
                 //Redirect to 404
            }
       }

Functions to encrypt and decrypt code

function string_encrypt($string = '') {
    return rtrim(strtr(base64_encode(@mcrypt_encrypt(
        MCRYPT_BLOWFISH,
        md5('sadsjdjaASajahj1233232SA', TRUE),
        utf8_encode($string),
        MCRYPT_MODE_ECB
    )), '+/', '-_'), '=');
}

function string_decrypt($string = '') {
    return str_replace("\000", '', @mcrypt_decrypt(
        MCRYPT_BLOWFISH,
        md5('sadsjdjaASajahj1233232SA', TRUE),
        base64_decode(str_pad(
            strtr($string, '-_', '+/'),
            strlen($string) % 4,
            '=',
            STR_PAD_RIGHT
        )),
        MCRYPT_MODE_ECB
    ));
}
PHP Ninja
  • 1,020
  • 1
  • 9
  • 27
0

Maybe you can save it with some kind of key-encryption algorithm like AES (Here is an php example) by using the orignal password hash encrypted with a key that couldn't be used by other browser like some browser data. Check get_browser or $_SERVER['HTTP_USER_AGENT'] This won't avoid someone use the same cookie in another browser with exact properties but you can find a way mixing some variables.

  • But the user-agent seems can fake by client easily(according to [link](https://thisinterestsme.com/php-set-curl-user-agent/)) – kevinHuang Dec 03 '19 at 13:25
  • Yes, user-agent as it can be changed by any user, but the "hacker" won't know what variables are you using to encrypt the hash into the cookie value (he/she won't know the algorithm you used neither ). if your AES key is `use user-agent + platform(from get_browser) + browser_name_regex (fromget_browser)` it will be to hard for someone to know the values of your key. – mauriciodelos Dec 03 '19 at 13:45