PHP session control session and cookie introduction
1. Cookie
1>Cookie introduction
Cookie is data stored in the client browser. User data can be tracked and stored through Cookie. Generally, cookies are returned from the server to the client through HTTP headers. Most web programs support the operation of cookies because cookies exist in HTTP headers.
_COOKIE[‘key’] to read a cookie value.
In PHP, the cookie is set through the setcookie function. For any cookie sent back from the browser, PHP will automatically store it in the form of
When using a session, a cookie is usually used to store the session ID to identify the user. The cookie has a validity period. When the validity period expires, the cookie will be automatically deleted from the client.
2>Set cookie
setcookie()
Meaning: Used to set cookies. There are 7 parameters in the setcookie() function (only 5 commonly used parameters).
Syntax: setcookie(name,value,expire,path,domain,secure,httponly)
Return value: If there is output before calling this function, setcookie() will fail and return FALSE. If setcookie() runs successfully, it will return TRUE. This does not indicate whether the user accepts cookies.
parameter:
value, time()+3600, “path/”, “baidu.com”); //Set the path and domain
name:
The name of the cookie, accessed through $_COOKIE[‘name’].
value:
Cookie value
expire:
The time when the cookie expires. This is a Unix timestamp in seconds. You can set it using the time() function plus the number of seconds you want it to expire before. Or you can use mktime(). If set to 0 or omitted, the cookie will expire at the end of the session (when the browser is closed), default is 0.
path:
(valid path) If the path is set to '/' then the entire website will be valid, if set to '/foo/' the cookie will only be in the /foo/ directory and all subdirectories like /foo/bar/ of Available domains.
domain:
(The domain where the cookie is available) By default, it is valid for the entire domain name. To make the cookie available for the entire domain (including all its subdomains), just set the value to the domain name (in this case, 'example.com').
secure:
Indicates that this cookie can only be transmitted over the client's secure HTTPS connection. When set to TRUE, the cookie will only be set if a secure connection exists. On the server side, programmers can only send this kind of cookie on a secure connection (eg: relative to
3>Cookie deletion and expiration time
There is no function to delete cookies specified in PHP. Instead, by setting the expiration time of the cookie to before the current time, the cookie will automatically expire. Thereby deleting the cookie.
4> Determine whether the cookie is empty
isset()
Meaning: Determine whether a cookie exists.
Syntax: isset (corresponding cookie attribute);
Return value: true/false
setcookie("name","SYN");if( isset( $_COOKIE["name"])){ echo $_COOKIE["name"]; }else{ echo "不存在"; }
Similarities and differences between Session and cookie
cookie:
1. Storing data on the client and establishing a connection between the user and the server can usually solve many problems, but cookies still have some limitations:
2. Cookies are relatively not very secure and can easily be stolen, leading to cookie fraud
3. The value of a single cookie can only store a maximum of 4k
4. Each request requires network transmission, occupying bandwidthsession:
1. Store the user's session data on the server, with no size limit,
2. User identification is performed through a session_id. By default in PHP, the session id is saved through cookies.
//开始使用sessionsession_start();//设置一个session$_SESSION['test'] = time();//显示当前的session_idecho "session_id:".session_id();echo "<br>";//读取session值echo $_SESSION['test'];//销毁一个sessionunset($_SESSION['test']);echo "<br>"; var_dump($_SESSION);
2. Session
1>session usage
First execute the session_start method to open the session, and then read and write the session through the global variable $_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, which will cause other concurrent accesses of the current user to be unable to execute and wait. This problem can be solved by using cache or database storage.
The session will automatically encode and decode the value to be set, so the session can support any data type, including data and objects.
session_start();$_SESSION['ary'] = array('name' => 'jobs');$_SESSION['obj'] = new stdClass(); var_dump($_SESSION);
2>Delete and destroy session
unset()
In PHP, use the unset function to delete a session value. 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不存在
session_destroy()
The session_destroy function will delete all data, but the session_id still exists.
session_start();$_SESSION['name'] = 'jobs';$_SESSION['time'] = time(); session_destroy();
Special Note:
_SESSION until it is empty, so if you need to destroy $_SESSION immediately, you can use unset().
session_destroy() will not immediately destroy the global variable
3>Use session to store user login information
登录信息既可以存储在sessioin中,也可以存储在cookie中,他们之间的差别在于session可以方便的存取多种数据类型,而cookie只支持字符串类型,同时对于一些安全性比较高的数据,cookie需要进行格式化与加密存储,而session存储在服务端则安全性较高。
<?phpsession_start();//假设用户登录成功获得了以下用户数据$userinfo = array( 'uid' => 1011, 'name' => 'spark', 'email' => '1637167XX@qq.com', 'sex' => 'F'); header("content-type:text/html; charset=utf-8");/* 将用户信息保存到session中 */$_SESSION['uid'] = $userinfo['uid'];$_SESSION['name'] = $userinfo['name'];$_SESSION['userinfo'] = $userinfo;//* 将用户数据保存到cookie中的一个简单方法 */$str =serialize($userinfo); //将用户信息序列化setcookie('userinfo', $str);
了解更多关于序列化serialize;
相关推荐:
The above is the detailed content of PHP session control session and cookie introduction. 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

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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
