作者在 2014-04-11 17:02:27 发布以下内容
使用mcrypt对cookie值进行可逆加密,浏览器端存储的是加密过得值,可以当session用。
//配置部分
$config['cookie_prefix'] = 'bccn_';
$config['cookie_domain'] = 'bccn.net';
$config['cookie_path'] = '/';
$config['cookie_skey'] = 'jewhdfy234957632946w32trweyugtfrhsdgfa';
//实现函数部分
function set_cookie($key, $value, $expire=2400, $secure=false, $httponly=true){
global $config;
$key = $config['cookie_prefix'] . $key;
$value = encrypt($value, $config['cookie_skey']);
setcookie($key, $value, time()+$expire, $config['cookie_path'], $config['cookie_domain'], $secure, $httponly);
}
function get_cookie($key){
global $config;
$key = $config['cookie_prefix'] . $key;
if(array_key_exists($key, $_COOKIE)){
return decrypt($_COOKIE[$key], $config['cookie_skey']);
}else{
return '';
}
}
function del_cookie($key){
global $config;
$key = $config['cookie_prefix'] . $key;
if(array_key_exists($key, $_COOKIE)){
setcookie($key, '', time()-3600, $config['cookie_path'], $config['cookie_domain'], false, false);
}
}
//加密解密函数
function encrypt($str, $skey){
$skey = substr($skey, 0, 56);
$td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $skey, $iv);
$encrypted_str = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$encrypted_str = bin2hex($encrypted_str);
return $encrypted_str;
}
function decrypt($str, $skey){
$str = hex2bin($str);
$skey = substr($skey, 0, 56);
$td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $skey, $iv);
$decrypted_str = mdecrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $decrypted_str;
}
//测试
set_cookie('test', 'hello world! 哈哈');
//del_cookie('test');
echo get_cookie('test');