至尊技术网 - 用户登录 https://www.zzwws.cn/tag/%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95/ PHP cookie加密登录与验证 https://www.zzwws.cn/archives/6366/ 2022-10-19T22:15:00+08:00 想要简单一点的可以用session,但session是创建会话,也会创建文件,这样文件会越来越多,会有些影响,所以用cookie会更好一点!<?php /** * cookie加密登录与验证 * @param array $userInfo 用户信息 * @param bool $validate 是否为验证或者填入token值验证,默认为false * @param int $expiresTime 过期时间,默认为1天 * @param string $tag token标签,默认为zz_token * @return bool|string */ function zz_login($userInfo, $validate = false, $expiresTime = 1, $tag = 'zz_token') { $salt = zz_salt(); $host = $_SERVER['HTTP_HOST']; if (!$salt) { return false; } if (!$validate) { try { $expiresTime = time() + 3600 * 24 * $expiresTime; $token = base64_encode(json_encode(['userInfo' => $userInfo, 'domain' => $host, 'expiresTime' => $expiresTime, 'code' => md5(json_encode($userInfo) . $host . $expiresTime . $salt)])); setcookie($tag, $token, $expiresTime, '/'); return $token; } catch (Exception $e) { return false; } } else { if($validate === true){ if (empty($_COOKIE[$tag])) { return false; } $arr = json_decode(base64_decode($_COOKIE[$tag]), true); }else{ $arr = json_decode(base64_decode($validate), true); } if (empty($arr['userInfo']) || empty($arr['domain']) || $arr['domain'] != $host || empty($arr['code']) || empty($arr['expiresTime']) || $arr['expiresTime'] <= time()) { return false; } return $arr['code'] === md5(json_encode($arr['userInfo']) . $host . $arr['expiresTime'] . $salt); } return true; } /** * 生成安全码 * @return string */ function zz_salt() { $root = $_SERVER['DOCUMENT_ROOT']; $file = $root.'/salt.php'; if(is_file($file)){ include($file); if(empty($salt) || empty($saltRoot) || $saltRoot != $root){ $salt = rand_str(20,true); file_put_contents($file,"<?php \r\n\$salt = '{$salt}';\r\n\$saltRoot = '{$root}';"); } }else{ $salt = rand_str(20,true); file_put_contents($file,"<?php \r\n\$salt = '{$salt}';\r\n\$saltRoot = '{$root}';"); } return $salt; } /** * 生成随机字符串 * @param int $num 字符串位数,默认为6 * @param bool $special 使用特殊字符,默认为false * @return string */ function rand_str($num = 6,$special = false) { $str = 'abcedfghjkmnpqrstuvwxyzABCEDFGHJKMNPQRSTUVWXYZ0123456789'; if($special){ $str .= '!@#$%^&*'; } return substr(str_shuffle($str), 0, $num); } // 登录 $userInfo = ['id' => 1,'username' => 'admin']; zz_login($userInfo); // 验证 if(zz_login('',true)){ echo '登录'; }else{ echo '未登录'; } // 获取用户信息 $arr = json_decode(base64_decode($_COOKIE['zz_token']),true); print_r($arr['userInfo']);