Home  >  Article  >  Backend Development  >  How to store php user information cache

How to store php user information cache

尚
Original
2019-10-29 10:37:003312browse

How to store php user information cache

php can save user information in session or cookie.

<?php
session_start();
//假设用户登录成功获得了以下用户数据
$userinfo = array(
    &#39;uid&#39;  => 10000,
    &#39;name&#39; => &#39;spark&#39;,
    &#39;email&#39; => &#39;spark@imooc.com&#39;,
    &#39;sex&#39;  => &#39;man&#39;,
    &#39;age&#39;  => &#39;18&#39;
);
header("content-type:text/html; charset=utf-8");


/* 将用户信息保存到session中 */
$_SESSION[&#39;uid&#39;] = $userinfo[&#39;uid&#39;];
$_SESSION[&#39;name&#39;] = $userinfo[&#39;name&#39;];
$_SESSION[&#39;userinfo&#39;] = $userinfo;


//* 将用户数据保存到cookie中的一个简单方法 */
$secureKey = &#39;334246&#39;; //加密密钥
$str = serialize($userinfo); //将用户信息序列化
//用户信息加密前
$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($secureKey), $str, MCRYPT_MODE_ECB));
//用户信息加密后
//将加密后的用户数据存储到cookie中
setcookie(&#39;userinfo&#39;, $str);


//当需要使用时进行解密
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($secureKey), base64_decode($str), MCRYPT_MODE_ECB);
$uinfo = unserialize($str);
echo "解密后的用户信息:<br>";
print_r($uinfo);

PHP session variables are used to store information about the user session (session), or to change the settings of the user session (session). Session variables store information for a single user and are available to all pages in the application.

Cookies are often used to identify users. A cookie is a small file that a server leaves on a user's computer. Each time the same computer requests a page through the browser, the cookie will be sent to the computer. With PHP, you can create and retrieve cookie values.

Recommended: php server

The above is the detailed content of How to store php user information cache. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn