What does php session technology mainly include?
This article mainly explains the PHP conversation mechanism cookie and session.
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 sets cookies through the setcookie function. Any cookie sent back from the browser will be automatically stored in the global variable of $_COOKIE by PHP, so we can use $_COOKIE['key' ] to 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 session IDs to identify users. 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.
For the sake of website security, this site does not provide the cookie variable display function for the time being. Please test it locally;
Set cookies
PHP The most common way to set cookies is to use the setcookie function. Setcookie has 7 optional parameters. The first 5 we commonly use are:
name (Cookie name) can be accessed through $_COOKIE['name']
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 If the path is set to '/', the entire website is valid
domain (valid domain) By default, the entire domain name is valid. If 'www.imooc.com' is set, it is only valid in the www subdomain
$value = 'test'; setcookie("TestCookie", $value); setcookie("TestCookie", $value, time()+3600); //有效期一小时 setcookie("TestCookie", $value, time()+3600, "/path/", "imooc.com"); //设置路径与域
There is also a function setrawcookie for setting cookies in PHP. Setrawcookie is basically the same as setcookie. The only difference is that the value will not be automatically urlencoded, so urlencode must be performed manually when needed.
setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365);
Because cookies are set through HTTP headers, they can also be set directly using the header method.
header("Set-Cookie:cookie_name=value");
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. Deleting cookies in PHP is also achieved using the setcookie function.
setcookie('test', '', time()-1);
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.
header("Set-Cookie:test=1393832059; expires=".gmdate('D, d M Y H:i:s \G\M\T', time()-1));
gmdate is used here to generate Greenwich Mean Time to eliminate the impact of time difference.
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 It has some limitations:
Cookies are relatively not very secure and can easily be stolen, leading to cookie spoofing
The value of a single cookie can only store a maximum of 4k
Every request requires a network connection Transmission, occupied bandwidth
session stores the user's session data on the server side, with no size limit, and identifies the user through a session_id. By default, PHP session id is saved through a cookie, so from some To a certain extent, seesion relies on cookies. But this is not absolute. The session id can also be implemented through parameters. As long as the session id can be passed to the server for identification, the session can be used.
Using session
Using session in PHP is very simple. First execute the session_start method to open the session, and then read and write the session through the global variable $_SESSION.
session_start(); $_SESSION['test'] = time(); var_dump($_SESSION);
session will automatically encode and decode the value to be set, so session can support any data type, including data and objects.
session_start(); $_SESSION['ary'] = array('name' => 'jobs'); $_SESSION['obj'] = new stdClass(); var_dump($_SESSION);
By default, sessions are stored on the server in the form of files. Therefore, when a session is opened on a page, the session file will be exclusively occupied. This will cause other concurrent accesses of the current user to be unable to execute and wait. .
Delete and destroy session
To delete a session value, you can use PHP's unset function. After deletion, it will be removed from the global variable $_SESSION and cannot be accessed.
session_start(); $_SESSION['name'] = 'jobs'; unset($_SESSION['name']); echo $_SESSION['name']; //提示name不存在
If you want to delete all sessions, you can use the session_destroy function to destroy the current session. session_destroy will delete all data, but the session_id still exists.
session_start(); $_SESSION['name'] = 'jobs'; $_SESSION['time'] = time(); session_destroy();
值得注意的是,session_destroy并不会立即的销毁全局变量$_SESSION中的值,只有当下次再访问的时候,$_SESSION才为空,因此如果需要立即销毁$_SESSION,可以使用unset函数。
session_start(); $_SESSION['name'] = 'jobs'; $_SESSION['time'] = time(); unset($_SESSION); session_destroy(); var_dump($_SESSION); //此时已为空
如果需要同时销毁cookie中的session_id,通常在用户退出的时候可能会用到,则还需要显式的调用setcookie方法删除session_id的cookie值。
使用session来存储用户的登录信息
session可以用来存储多种类型的数据,因此具有很多的用途,常用来存储用户的登录信息,购物车数据,或者一些临时使用的暂存数据等。
用户在登录成功以后,通常可以将用户的信息存储在session中,一般的会单独的将一些重要的字段单独存储,然后所有的用户信息独立存储。
$_SESSION['uid'] = $userinfo['uid']; $_SESSION['userinfo'] = $userinfo;
一般来说,登录信息既可以存储在sessioin中,也可以存储在cookie中,他们之间的差别在于session可以方便的存取多种数据类型,而cookie只支持字符串类型,同时对于一些安全性比较高的数据,cookie需要进行格式化与加密存储,而session存储在服务端则安全性较高。
The above is the detailed content of What does php session technology mainly include?. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



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.

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.

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

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.
