有时候登陆需要记住密码功能,思路大致如下。如果用户勾选了记住密码,那么我们在登陆时,通过一套加密算法,算出一个值,然后将该值存写入cookie,这里是一个简单的加密算法:
这里加密算法比较简单,大家可以根据需求再适当做更改。本人新手,不喜勿喷
public static function enc_remember($c, $userid, $key)
{
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
if (strlen($key)>=$ks) $key = substr($key, 0, $ks);
else $key = str_pad($key, $ks, " ", STR_PAD_RIGHT);
$enciv = base64_encode($iv);
mcrypt_generic_init ($td, $key, $iv);
$expire = time () + Controller_Base::COOKIE_REMEMBER_LIFECYCLE;
$data_prefix = $userid.":".$enciv;
$encdata = mcrypt_generic($td, $key.":".$expire);
$data = $data_prefix.":".base64_encode($encdata);
mcrypt_generic_deinit ( $td );
mcrypt_module_close ( $td );
Cookie::set(Controller_Base::COOKIE_NAME_REMEMBER, $data,
Controller_Base::COOKIE_REMEMBER_LIFECYCLE);
}
当用户在下一次访问页面时,先看用户是否登陆(即session中是否已存放用户信息),如果未登陆则试着从cookie里取之前加密的信息,并解密判断,若符合则可直接从中获取用户信息,则证明已登陆。如下:
public static function dec_remember($c)
{
$remember = Cookie::get(Controller_Base::COOKIE_NAME_REMEMBER);
if (!$remember) return NULL;
list($userid, $enciv, $encdata) = explode(":", $remember);
$iv = base64_decode($enciv);
$encrypted = base64_decode($encdata);
/* 检查用户信息是否匹配 */
$user = Model_User::get_user_byid($userid);
if ($user) {
$key = $user['password'];
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$ks = mcrypt_enc_get_key_size($td);
if (strlen($key)>=$ks) $key = substr($key, 0, $ks);
else $key = str_pad($key, $ks, " ", STR_PAD_RIGHT);
mcrypt_generic_init ($td, $key, $iv);
$decrypted = mdecrypt_generic($td, $encrypted);
list($dec_key, $dec_expire) = explode(":", $decrypted);
if ($dec_expire >= time() && ($dec_key == $key)) {
return $user;
}
}
return NULL;
}
这里加密算法比较简单,大家可以根据需求再适当做更改。本人新手,不喜勿喷