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教程有兴趣的朋友有所帮助。

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

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