Table of Contents
Introduction to Cookies and Sessions
Cookie configuration and application
Session configuration and application
Home Backend Development PHP Tutorial Introduction to the basic use of sessions and cookies

Introduction to the basic use of sessions and cookies

Mar 19, 2017 am 10:15 AM

Introduction to Cookies and Sessions

Many times, we need to track visitors’ activities throughout the website and automatically or semi-automatically identify their identities (which is commonly referred to as website login and other functions) , at this time, we often use Cookie and Session to track and judge.

Session information is stored on the server side, but the session id is stored in the client cookie. Of course, PHP's session storage methods are diverse, so it can be tracked even if cookies are disabled.

Cookie is a mechanism that stores data on a remote browser to track and identify users. Cookies are completely kept on the client side, such as IE firefox. When the client disables cookies, they can no longer be used.

Setcookie(string name, string value, int expire,string path, string domain, int secure);
Copy after login

where name is the cookie variable name identifier. You will be able to use it to reference the cookie variable in PHP just like using ordinary variable names. value is the initial value of the cookie variable, expire represents the validity time of the cookie variable; path represents the relevant path of the cookie variable; domain represents the website of the cookie variable; secure is valid only when https is securely transmitted.

For example:

SetCookie("Cookie", "cookievalue", time()+3600, "/librarys", ".nowamagic.net", 1);
Copy after login

1. Receiving and processing Cookies

PHP has very good support for receiving and processing Cookies. It is completely automatic and similar to FORM variables. The principle is the same, very simple.

For example, if you set a cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a variable like an ordinary variable named $myCookie. The value of this variable It is the value of the cookie. The same applies to arrays. Another way is to reference PHP's global variable $HTTP_COOKIE_VARS array.

Examples are as follows: (assuming these have been set in previous pages and are still valid)

echo $MyCookie;
echo $CookieArray[0];
echo $_COOKIE["MyCookie"]; 
echo $HTTP_COOKIE_VARS["MyCookie"];
Copy after login

2. Delete Cookies

To delete an already There are two methods for existing cookies:

  • SetCookie("Cookie", "");

  • SetCookie("Cookie", " value", time()-1 / time() );

3. Restrictions on using cookies

  1. must be in the content of the HTML file Set before output;

  2. Different browsers handle cookies inconsistently, and sometimes incorrect results will occur.

  3. The limit is on the client side. The maximum number of cookies that can be created by a browser is 30, and each cookie cannot exceed 4KB. The total number of cookies that can be set by each WEB site cannot exceed 20.

Session configuration and application

session_start();		//初始化session.需在文件头部

$_SESSION[name]=value;	//配置Seeeion
echo $_SESSION[name];	//使用session
isset($_SESSION[name]);	// 判断
unset($_SESSION[name]);	//删除

session_destroy(); 		//消耗所有session
Copy after login

Note: session_register(), session_unregister, session_is_registered are no longer used under php5.

Cookie usage examples:

if($_GET['out'])
{   //用于注销cookies
    setcookie('id',"");
    setcookie('pass',"");
    echo "<script>location.href=&#39;login.php&#39;</script>"; //因为cookies不是及时生效的,只有你再次刷新时才生效,所以,注销后让页面自动刷新。
}

if($_POST[&#39;name&#39;]&&$_POST[&#39;password&#39;]) //如果变量用户名和密码存在时,在下面设置cookies
{   //用于设置cookies
    setcookie(&#39;id&#39;,$_POST[&#39;name&#39;],time()+3600);
    setcookie(&#39;pass&#39;,$_POST[&#39;password&#39;],time()+3600);
    echo "<script>location.href=&#39;login.php&#39;</script>"; //让cookies及时生效
   
}
if($_COOKIE[&#39;id&#39;]&&$_COOKIE[&#39;pass&#39;])
{   //cookies设置成功后,用于显示cookies
    echo "登录成功!<br />用户名:".$_COOKIE[&#39;id&#39;]."<br/>密码:".$_COOKIE[&#39;pass&#39;];
    echo "<br />";
    echo "<a href=&#39;login.php?out=out&#39;>注销cookies</a>";  //双引号内,如果再有引号,需要用单引号。
}

?>
<form action="" method="post">
用户ID:
<input type="text" name="name" /><br/><br/>
密码:
<input type="password" name="password" /><br/><br />
<input type="submit" name="submit">
</form>
Copy after login

session usage examples:

<?php
//session用法实例
session_start();//启动session,必须放在第一句,否则会出错。
if($_GET[&#39;out&#39;])
{
      

    unset($_SESSION[&#39;id&#39;]);
    unset($_SESSION[&#39;pass&#39;]);
}

if($_POST[&#39;name&#39;]&&$_POST[&#39;password&#39;])
{   
   //用于设置session
    $_SESSION[&#39;id&#39;]=$_POST[&#39;name&#39;];
    $_SESSION[&#39;pass&#39;]=$_POST[&#39;password&#39;];
}

if($_SESSION[&#39;id&#39;]&&$_SESSION[&#39;pass&#39;])
{
    echo "登录成功!<br/>用户ID:".$_SESSION[&#39;id&#39;]."<br />用户密码:".$_SESSION[&#39;pass&#39;];
    echo "<br />";
    echo "<a href=&#39;login.php?out=out&#39;>注销session</a>";
}


?>
<form action="login.php"  method="post">
用户ID:
<input type="text" name="name" /><br/><br/>
密码:
<input type="password" name="password" /><br/><br />
<input type="submit" name="submit">
</form>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

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.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

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.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

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 PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

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

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

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.

How cookies work How cookies work Sep 20, 2023 pm 05:57 PM

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.

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

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

What are the dangers of cookie leakage? What are the dangers of cookie leakage? Sep 20, 2023 pm 05:53 PM

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.

See all articles