php session control session&cookie
Introduction to cookies
Cookies are data stored in the client's browser. We use cookies to track and store user data. Typically, cookies are returned from the server to the client via HTTP headers. Most web programs support the operation of cookies. Because cookies exist in the HTTP header, they must be set before other information is output, similar to the usage restrictions of the header function.
PHP uses the setcookie function to set cookies. Any cookie sent back from the browser will be automatically stored in the global variable of $_COOKIE by PHP, so we can use the form of $_COOKIE['key'] Read a cookie value.
Cookies in PHP are very widely used and are often used to store users' login information, shopping carts, etc. When using a session, cookies are usually used to store the session id to identify the user. Cookies have a validity period. When the validity period expires, , the cookie will be automatically deleted from the client. At the same time, for security control, Cookie can also set domain and path. We will explain them in detail in later chapters.
Set cookies
The most common way to set cookies in PHP is to use the setcookie function. setcookie has 7 optional parameters, and the first 5 we commonly use are:
name (Cookie name) can be passed $_COOKIE[' name'] to access
value (Cookie value)
expire (expiration time) Unix timestamp format, the default is 0, which means it will expire when the browser is closed
path (valid path) if the path is set to '/ ', the entire website is valid
domain (valid domain) The entire domain name is valid by default. If 'www.imooc.com' is set, it is only valid in the www subdomain
There is also a setting in PHP Cookie's function setrawcookie, setrawcookie is basically the same as setcookie. The only difference is that the value value will not be automatically urlencoded, so it must be urlencoded manually when needed.
Because cookies are set through HTTP headers, they can also be set directly using the header method.
Cookie deletion and expiration time
Through the previous chapters, we learned about the function of setting cookies, but we found that there is no function to delete cookies in PHP. The setcookie function is also used to delete cookies in PHP. accomplish.
You can see that if the expiration time of the cookie is set before the current time, the cookie will automatically expire, thus achieving the purpose of deleting the cookie. The reason for this design is that cookies are passed through HTTP headers. The client sets cookies based on the Set-Cookie segment returned by the server. If deleting cookies requires using a new Del-Cookie, the HTTP header It will become complicated. In fact, the setting, updating and deletion of cookies can be achieved simply and clearly through Set-Cookie.
After understanding the principle, we can also delete cookies directly through the header.
gmdate is used here to generate Greenwich Mean Time to eliminate the impact of time difference.
Valid path of the cookie
The path in the cookie is used to control which path the set cookie is valid in. The default is '/', which is available in all paths. When other paths are set, then It is only valid under the set path and sub-path. For example:
The above settings will make test valid under /path and sub-path /path/abc, but the test cookie cannot be read in the root directory. value.
Under normal circumstances, most of them use all paths. Only in rare cases where there are special needs, the path will be set. In this case, the cookie value will only be passed in the specified path, which can save data transmission and enhance security and improved performance.
When we set a valid path, the current cookie cannot be seen if it is not in the current path.
Session and Cookie Similarities and Differences
Cookie stores data on the client and establishes a connection between the user and the server. It can usually solve many problems, but cookies still have some limitations:
Cookies are relatively not It is too safe and easy to be stolen, leading to cookie spoofing
The value of a single cookie can only store up to 4k
Every request requires network transmission, which takes up bandwidth
session是将用户的会话数据存储在服务端,没有大小限制,通过一个session_id进行用户识别,PHP默认情况下session id是通过cookie来保存的,因此从某种程度上来说,seesion依赖于cookie。但这不是绝对的,session id也可以通过参数来实现,只要能将session id传递到服务端进行识别的机制都可以使用session。
使用session
在PHP中使用session非常简单,先执行session_start方法开启session,然后通过全局变量$_SESSION进行session的读写。
session会自动的对要设置的值进行encode与decode,因此session可以支持任意数据类型,包括数据与对象等。
默认情况下,session是以文件形式存储在服务器上的,因此当一个页面开启了session之后,会独占这个session文件,这样会导致当前用户的其他并发访问无法执行而等待。可以采用缓存或者数据库的形式存储来解决这个问题。
删除与销毁session
删除某个session值可以使用PHP的unset函数,删除后就会从全局变量$_SESSION中去除,无法访问。
如果要删除所有的session,可以使用session_destroy函数销毁当前session,session_destroy会删除所有数据,但是session_id仍然存在。
值得注意的是,session_destroy并不会立即的销毁全局变量$_SESSION中的值,只有当下次再访问的时候,$_SESSION才为空,因此如果需要立即销毁$_SESSION,可以使用unset函数。
如果需要同时销毁cookie中的session_id,通常在用户退出的时候可能会用到,则还需要显式的调用setcookie方法删除session_id的cookie值。
使用session来存储用户的登录信息
session可以用来存储多种类型的数据,因此具有很多的用途,常用来存储用户的登录信息,购物车数据,或者一些临时使用的暂存数据等。
用户在登录成功以后,通常可以将用户的信息存储在session中,一般的会单独的将一些重要的字段单独存储,然后所有的用户信息独立存储。
一般来说,登录信息既可以存储在sessioin中,也可以存储在cookie中,他们之间的差别在于session可以方便的存取多种数据类型,而cookie只支持字符串类型,同时对于一些安全性比较高的数据,cookie需要进行格式化与加密存储,而session存储在服务端则安全性较高。
session_start();//假设用户登录成功获得了以下用户数据
$userinfo = array(
'uid' => 10000,
'name' => 'spark',
'email' => 'spark@imooc.com',
'sex' => 'man',
'age' => '18'
);
header("content-type:text/html; charset=utf-8");
/* 将用户信息保存到session中 */
$_SESSION['uid'] = $userinfo['uid'];
$_SESSION['name'] = $userinfo['name'];
$_SESSION['userinfo'] = $userinfo;
echo "welcome ".$_SESSION['name'] . '
';
//* 将用户数据保存到cookie中的一个简单方法 */
$secureKey = 'imooc'; //加密密钥
$str = serialize($userinfo); //将用户信息序列化
echo "用户信息加密前:".$str;
$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secureKey, $str, MCRYPT_MODE_ECB));
echo "用户信息加密后:".$str;
//将加密后的用户数据存储到cookie中
setcookie('userinfo', $str);
//当需要使用时进行解密
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secureKey, base64_decode($str), MCRYPT_MODE_ECB);
$uinfo = unserialize($str);
echo "解密后的用户信息:
";
var_dump($uinfo);
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了php会话控制session&cookie,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

The famous activation script MAS2.2 version supports digital activation again. The method originated from @asdcorp and the team. The MAS author calls it HWID2. Download gatherosstate.exe (not original, modified) from https://github.com/massgravel/Microsoft-Activation-Scripts, run it with parameters, and generate GenuineTicket.xml. First take a look at the original method: gatherosstate.exePfn=xxxxxxx;DownlevelGenuineState=1 and then compare with the latest method: gatheros

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains
