Example of Session management Cookie and Session in PHP-PHP source code

Source: Internet
Author: User
Tags php session send cookies
In PHP, session management includes common sessions and cookies, which are two sessions on the server and client respectively. Let's take a look at them. In PHP, session management includes common sessions and cookies, which are two sessions on the server and client respectively. Let's take a look at them.

Script ec (2); script

Session management is an important part of web development, including Session and Cookie technologies. This chapter describes how to create and use cookies and sessions.


Cookies are often used to identify users. Cookie is a small file that the server stays on the user's computer. When the same computer requests a page through a browser, it sends a cookie at the same time. You can use PHP to create and retrieve the cookie value. A cookie can only be read from the domain where it is located. A single domain cannot contain more than 20 cookies. The length of each cookie file is limited to 4 K Bytes. A browser can store up to 300 cookies.

Cookie creation:

The setcookie () function is used to set the cookie. Note: The setcookie () function must be located before the tag.


* Name: required. Specifies the cookie name.
* Value: required. Specifies the cookie value.
* Expire: Optional. Specifies the cookie validity period.
* Path: Optional. Specifies the server path of the cookie.
* Domain: Optional. Specifies the Domain Name of the cookie.
* Secure: Optional. Specifies whether to transmit cookies through secure HTTPS connections.
Setcookie (name, value, expire, path, domain, secure)
Note: When sending a cookie, the cookie value is automatically URL encoded. URL Decoding is performed when receiving the message.


1. Set and send cookies:

$ Value = "my cookie value ";

// Send a simple cookie
// Cookie24 hour expired
Setcookie ("TestCookie", $ value, time () + 3600*24 );

2. Different Methods for retrieving cookie values:

// Output individual cookies
Echo $ _ COOKIE ["TestCookie"];
Echo $ HTTP_COOKIE_VARS ["TestCookie"];

// Output all cookies
Print_r ($ _ COOKIE );

3. Output

My cookie value
My cookie value
Array ([TestCookie] => my cookie value)

4. delete a cookie

Delete a cookie by setting the expiration date to the past date/time:

// Set the expiration date to one hour ago
Setcookie ("TestCookie", "", time ()-3600 );


The PHP session variable is used to store information about a user session or change the settings of a user session. Session variables are stored by a single user and can be used on all pages of the application. The Session mechanism is to create a unique id (UID) for each visitor and store the variables based on the UID. The UID is stored in the cookie or transmitted through the URL.

Session creation:

Before you store user information in a PHP session, you must start the session. The session_start () function must be located before the tag.


Session_start ();


1. Start session

2. Store session Variables

The correct method for storing and retrieving session variables is to use the $ _ SESSION variable:

Session_start ();
// Store session data
$ _ SESSION ['view'] = 1;

// Retrieve session data
Echo "Pageviews =". $ _ SESSION ['view'];

3. Output

Pageviews = 1

4. Terminate the session
If you want to delete some session data, you can use the unset () or session_destroy () function.
The unset () function is used to release the specified session variable:

Unset ($ _ SESSION ['view']);

You can also use the session_destroy () function to completely terminate the session:

Session_destroy ();

Set the display information after User Logon Through session

At the top of the website, there are usually user logon and registration portals. After a user logs on, the user information should be displayed, such as the account, and the logon portal should be changed to exit;

In the symphony template, you can use the following code:

Hello {app. session. get ('Member _ name')}, welcome to ** network!

{% If app. session. get ('Member _ name') = null %}

  • Login

  • Register

  • {% Elseif app. session. get ('Member _ name ')! = "" %}

  • Exit

  • {% Endif %}
    First use {% if app. session. get ('Member _ name') = "" %}

    Later, an error is reported, and then it is changed to null, which indicates whether a user's logon session is successful.

    Differences between SESSION and COOKIE in PHP

    The Difference and connection between the two are actually very profound. I always know something about it. I have to go online every time and write it down today. I will take a look at it every time to deepen my memory.
    Session is a server-side storage space maintained by the application server. When you connect to the server, the server generates a unique SessionID, use this SessionID as the identifier to access the Session bucket on the server. SessionID is saved to the client and saved using cookies. When a user submits a page, the SessionID is submitted to the server to access Session data. This process requires no developer intervention. Therefore, once the Cookie is disabled on the client, the Session will also become invalid.

    The server can also pass the SessionID value through URL rewriting, so it is not completely dependent on cookies. If the client Cookie is disabled, the server can automatically save the Session value by rewriting the URL, and this process is transparent to the programmer.

    You can try to use the request even if no Cookie is written. getCookies (); the length of the retrieved Cookie array is also 1, and the Cookie name is JSESSIONID. There is also a long binary string, which is the value of SessionID.

    As we all know, http is a stateless protocol. Each time a customer reads a web page, the server opens a new session, and the server does not automatically maintain the customer's context information, so how can we implement the shopping cart in the online store? session is a mechanism for storing context information. It targets every user and stores the variable values on the server, session IDs are used to differentiate different customers. sessions are implemented based on cookies or URL rewriting. By default, the system creates an output cookie named JSESSIONID, which is called session cookie, in order to distinguish persistent cookies, that is, the cookie we usually call. Note that session cookies are stored in the browser memory and are not written to the hard disk. This is the JSESSIONID we just saw, we usually cannot see JSESSIONID, but when we disable the cookie of the browser, the web server will use URL rewriting to pass Sessio Nid, we can see strings such as sessionid = KWJHUG6JJM65HS2K6 in the address bar.

    After understanding the principles, we can easily distinguish the differences between persistent cookies and session cookies. The discussions on the security of the two on the Internet are clear. session cookies are for a session, session cookie disappears, while the persistent cookie is only a piece of text (usually encrypted) stored on the client's hard disk ), in addition, cookie spoofing and cross-site scripting attacks against cookies are not as secure as session cookies.

    Generally, session cookies cannot be used across windows. When you open a new browser window to enter the same page, the system will give you a new sessionid, in this way, we cannot achieve the purpose of information sharing. At this time, we can first save the sessionid in the persistent cookie, and then read it out in the new window to get the SessionID of the previous window, in this way, session cookie and persistent cookie are combined to achieve cross-window session tracking ).

    In some web development books, Session and cookie are usually used as two parallel http transmission methods. session cookies are on the server side, and persistent cookies are on the client side, however, session is based on cookies. It is not difficult to select the appropriate technology to develop web services by understanding the relationship and difference between the two.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.