Examples of Session management cookies and sessions in PHP

Source: Internet
Author: User
Tags change settings php session send cookies sessions setcookie unique id

Session management is an important part of web development, including sessions and cookie two technologies. This chapter describes the creation and use of cookies and sessions.


Cookies are often used to identify users. Cookies are small files that the server leaves on the user's computer. Whenever the same computer requests a page through a browser, it sends cookies as well. The value of a cookie can be created and retrieved through PHP. Cookies can only read the domain, the single domain can not exceed 20 cookies, each cookie file length of up to 4k bytes, the browser stores up to 300 cookies.

Creation of cookies:

The Setcookie () function is used to set cookies. Note: the Setcookie () function must precede the label.


* Name: Required. Specify the name of the cookie.
* Value: Required. Specify the value of the cookie.
* Expire: Optional. Specify the expiration date of the cookie.
* Path: Optional. Specify the server path for the cookie.
* Domain: Optional. Specify the domain name of the cookie.
* Secure: Optional. Specify whether to transmit cookies through a secure HTTPS connection.
Setcookie (Name,value,expire,path,domain,secure)
Note: When you send a cookie, the value of the cookie is automatically URL-coded. The URL is decoded when it is received.


1. Set up and send cookies:

$value = "My cookie value";

Send a simple cookie
Cookie24 hours Expired
Setcookie ("TestCookie", $value, Time () +3600*24);

2. Different ways to retrieve cookie values:


To output individual cookies
echo $_cookie["TestCookie"];
echo "
echo $HTTP _cookie_vars["TestCookie"];
echo "

Output All Cookies
Print_r ($_cookie);

3. Output

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

4. Delete Cookies

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 user sessions, or to change settings for user sessions. The session variable holds information that is a single user and is available to all pages in the application. The session works by creating a unique ID (UID) for each visitor and storing the variables based on this UID. The UID is stored in a cookie or transmitted through a URL.

Creation of Session:

Before you store the user information in the PHP session, you must first start the conversation. The Session_Start () function must precede the label.


Session_Start ();


1. Start session

<?php session_start ();?>

2. Store Session variable

The correct way to store and retrieve session variables is to use the $_session variable:

Session_Start ();
Store session Data
$_session[' views ']=1;

Retrieve session data
echo "pageviews=". $_session[' views '];

3. Output


4. End Session
If you want to delete some session data, you can use the unset () or Session_destroy () function.
The unset () function frees the specified session variable:

unset ($_session[' views ');

You can also completely end the session through the Session_destroy () function:

Session_destroy ();

Set the display information after the user logs in by session

At the top of the site there will usually be a user login and registration of the entrance, and after the user login, to display the user's information, such as account number, and the login to the entry into the exit;

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

<span> Hello </span><span style= "color: #009cff;" >{{app.session.get (' member_name ')}}</span><span> Welcome to * * * Net! </span>

{% if App.session.get (' member_name ') = = null%}
<li><a href= "{{path (' Zm_member_login ')}}" > Login </a></li>
<li><a href= "{{path (' Zm_member_register ')}}" > Registration </a></li>
{% ElseIf app.session.get (' member_name ')!= ""%}

<li><a href= "{{path (' Zm_member_logout ')}}" > Exit </a></li>

{% ENDIF%}
First Use {% if App.session.get (' member_name ') = = "%}"

Later, the total error will be changed to NULL, that is, you can determine whether there is a successful user login session.

The difference between session and Cookie in PHP

The two, the difference and connection is also very abstruse, always understand some fur, every time have to go online, write down today, every time to look at, deepen memory.
Session is a server-side storage space maintained by the application server, and when users connect to the server, a unique SessionID is generated by the server, using the SessionID as an identifier to access the server-side session storage space. And SessionID this data is saved to the client, saved with cookies, when the user submits the page, the SessionID is submitted to the server side to access the session data. This is a process that is not interfered with by developers. So once the client disables cookies, the session is invalidated.

The server can also pass SessionID values through URL rewriting, so it is not entirely dependent on cookies. If the client cookie is disabled, the server can automatically save the session value by overriding the URL, and the process is transparent to the programmer.

You can try it, even if you don't write cookies, use Request.getcookies (), and the length of the cookie array is 1, and the cookie's name is Jsessionid, and there's a very long binary string, Is the value of the SessionID.

As we all know, HTTP is a stateless protocol, every time the client reads the Web page, the server opens a new session, and the server will not automatically maintain the client's contextual information, then how to implement the online store shopping cart, session is a mechanism to save contextual information, It is for each user, the value of the variable is stored on the server side, through the sessionid to distinguish between different customers, session is based on cookie or URL rewrite, the default use of cookies to implement, The system creates an output cookie called Jsessionid, which we call the session cookie to differentiate the persistent cookies, which is what we usually call cookies, note session Cookies are stored in the browser memory, not on the hard drive, which is what we just saw jsessionid, we usually do not see the jsessionid, but when we put the browser cookie ban, The Web server uses URL rewriting to pass SessionID, and we can see strings like sessionid=kwjhug6jjm65hs2k6 in the address bar.

Understand the principle, we can easily distinguish between the persistent cookies and the session cookie, the Internet on the security of the discussion is also at a glance, a session cookie for a conversation, Sessions end The cookie disappears, and the persistent cookie is just a piece of text (usually encrypted) that exists on the client's hard disk, and can be compromised by cookie spoofing and cross-site scripting against cookies, which is naturally less secure than the session cookie.

Usually the session cookie is not used across windows, and when you open a new browser window into the same page, the system gives you a new SessionID, so that the purpose of our information sharing is not reached, At this point we can save the SessionID in a persistent cookie and then read it in a new window to get the previous window SessionID, so that the session cookie and persistent The combination of cookies enables us to implement a cross window session tracking (conversation tracking).

In some web development books, it is often simply the way to send sessions and cookies as two parallel HTTP messages, session cookies are on the server side, and persistent cookies are located on the client, But the session is based on cookies, understand the relationship between the two and the difference, we will not be difficult to choose the right technology to develop Web service.

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.