


A brief analysis of cookie and session technology in PHP_PHP Tutorial
A brief analysis of cookie and session technology in PHP
1.What are cookies?
Cookie refers to the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and perform session tracking.
To put it simply, you go to a specialty store or supermarket to buy something, and then the store will apply for a membership card for you. In the future, your identity and purchase information will be stored in this card, and this card will store your On the body. After that, you only need to swipe the card every time you go to buy something, and there is no need to register or record other information.
Then map this paragraph to the web. The supermarket checkout counter is the server, and you yourself are the client. The card you carry is the cookie file stored in the client, which records you. account password and other information.
However, one thing to note is that the cookie will only take effect the second time it is used. That is to say, when you buy something for the first time in the supermarket, they will apply for a card for you, and you can swipe the card for future purchases. However, before the first purchase, the supermarket does not have any information about you, so you don’t have a card at all for the first time. The same goes for websites. When you log in to a website for the first time, of course you have to enter your account, password and other information, and then you can generate a cookie and store it locally for next time use.
At the same time, cookies also have their own validity period. After the expiration, they will become invalid and the local cookie files will be automatically deleted. You need to log in again, enter your account and password, and then generate a new cookie. The main purpose of doing this is for safety reasons.
2. Cookie mechanism diagram.
3. How to use cookies.
(1) Set cookie
bool setcookie ( string $name,$value,$expire,$path,$domain,$secure,$httponlyFor example:
setcookie("username","user",0,"/"); setcookie("username","user",time()+60*60,"/");
The usage of each parameter will not be explained. Here we focus on analyzing the time and path in the above two methods of setting cookies.
Put a 0 in the first time, does it mean that the survival time is 0. It is obviously impossible. It has a special meaning, indicating that the validity period of the cookie ends when the browser is closed. They all put a "/" in their paths. This means that all content paths under this domain name can access the cookie, which means that all pages under this website can track this cookie.
(2) Delete cookies
setcookie("username","",time()-3600,"/");It is the same thing as setting a cookie, except that there is no cookie value, the time is earlier than the current time, and then it expires.
(3) View cookies
print_r($_COOKIE);Everyone must know this guy, so just waste your eyes on him.
-------------------------------------------------- ----------------------------------------
-----------------------------I am the dividing line---------- --------------------------------
-------------------------------------------------- ----------------------------------
1.What is session?
Session refers to the time interval between an end user communicating with the interactive system, usually referring to the time elapsed from registering to enter the system to logging out of the system.
The working principle of session (excerpted from Baidu) (1) When a session is enabled for the first time, a unique identifier is stored in a local cookie. (2) First use the session_start() function, and PHP loads the stored session variables from the session warehouse. (3) When executing a PHP script, register the session variable by using the session_register() function. (4) When the PHP script execution ends, the session variables that have not been destroyed will be automatically saved in the local session library under a certain path. This path can be specified by session.save_path in the php.ini file. The next time you browse the web page Can be loaded and used.
In fact, in layman's terms, when you go to the supermarket to buy things, the membership card you apply for records your information. However, the membership card is not saved with you, but is stored in the supermarket's system as data. Once registered, you can directly use. You can use it directly when you need it. But once you leave the supermarket, that membership card loses its validity until your next purchase. At the same time, the only identification of this membership card is you, and no one else can use your membership card. It's easy to understand if you directly take the seat.
One big difference between session and cookie is that session is used directly after registration, that is, it can be used after the first purchase, while cookie information is stored in the membership card after the first purchase, and then starts to be used the second time.
2. Diagram of session mechanism.
3. How to use session.
(1) Set session
session_start();
$_SESSION['username']="user";
每一次在使用session之前都需要进行开启session,就当是通常进门都先需要开门一样。而在设置session时和对变量进行赋值没有多大的区别,其实$_SESSION本身就是一个变量。
(2)删除session
这个相对步骤就多了点,而不是cookie里面一句话搞定。
//开启session session_start(); //注销session session_unset(); //销毁session session_destroy(); //同时销毁本地cookie中的sessionid setcookie(session_name(),"",time()-3600,"/");(3)查看session
print_r($_SESSION);
1.cookie与session优缺点。
cookie本身是存放在客户端中,仅占用几kb的内存大小。每次登录网站的时候都会带上本地的cookie进行验证,省去了麻烦的重复输入。但是安全性不是很高,毕竟是存放在本地的文件,虽然都是进行加密了的,一旦电脑数据被盗取,cookie就很有可能会被获取。
session存放在服务器中,占中内存虽小,但是用户基数够大的情况下,会对服务器造成很大的负荷。但是,数据放在服务器上,总归风险降低了许多。虽说没有不透风的墙,不过风也是可以很小很小的,这比喻。。。有同学可能疑问,session使用时,会有sessionid存在本地,一旦获取能否登录。答案当然是否定的,因为每次的id都是不一样的。

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.


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

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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