PHP Session Management and control

Source: Internet
Author: User
Tags php session setcookie

Session Overview

We know that cookies are kept connected to the server by keeping the data on the client side, and the session is maintained by keeping the data on the servers.

We took a small example of the meeting before:

When people meet in a few decades ago, they need to bring a conference card. This attendance card has the person's position, name, unit, photograph and other information. At the meeting, the Conference security personnel, the organizers only need to check the relevant information on the line.

This small example mainly shows that people take their own attendance cards with their own information. This mode is a cookie.

The computer has this cookie information in the computer's hard drive.

where does a cookie exist? the essence of a cookie is a small piece of data, a small piece of data stored on your computer's hard drive. But where does it exist? Come on, let's find out.

The path to the cookie file for the Chrome browser is:
C:\Users\ your user name \appdata\local\google\chrome\user data\default\cookies

The cookie file path for the Firefox browser is:
C:\Users\ your username \appdata\roaming\mozilla\firefox\profiles\rdgp36vl.default\cookies.sqlite Everyone may be slightly different

Open the cookie file with a text editor to see the garbled, we have to use the tool to view, such as:

Let's take a look at a few of the columns that we need to focus on, domain is the website that the cookie belongs to, name is the name of the cookies, value is the cookie, and expires represents the expiration date of the cookie.

Using a familiar website example, tudou.com, we can see that there are 4 cookies on tudou.com, so when we visit tudou.com, the browser automatically sends the Name and Value of the 4 cookies to tudou.com This URL point to the server (PS: must be within the validity period, beyond the expiration date will not be sent to the server, the validity period we can depend on the demand), so that the server can be based on this information to maintain the connection with the client, popular point, It is the data that can be used to know that you are you. When the server receives these cookies, it will do some processing according to their values, what to do? It depends on what the developers want to do with this information!

PHP session-controlled Cookies in PHP

In this section, we use a user's first login to the website to learn about cookies without having to re-enter the user name and password.

First, let's introduce the method of setting cookies in PHP.
PHP provides a function to let us set cookies, this function is:

 bool   Setcookie ( string   $ name [,  string   int  $ expiration time = 0   "[,  string   $ path] [,  string  bool  $ security = false   [,  bool  $http Read only = false  ]);  

Parameter description
$ name required. Specifies the name of the cookie.
The $ value is optional. Specifies the value of the cookie.
The $ validity period is optional. Specify the validity period of the cookie.
The $ path is optional. Specifies the server path of the cookie.
The $ domain name is optional. Specifies the domain name of the cookie.
$ security is optional. Specifies whether to transfer cookies through a secure HTTPS connection.
$http an optional reading. If true, then JS will not be able to read the change cookie, increase security.

In general, we actually do not have so many parameters above, for this function, we generally use: Setcookie (cookie name, cookie value, cookie expiration date);

Yes, that's 3. As a result, we can read the COOKIE through $_cookie[' name ' on the server.

The following is an example:
We name the file name: cookie.php.

Let's simulate the most common example of what we see on the Internet: the process of entering a user name and password to login successfully.

Let's build a database login, which has the table user, with the username and password fields.

<?PHP//The first time you log in, the user input information to confirm the userif(($_post['username'] !=NULL) && ($_post['Password'] !=NULL) {$userName= $_post['username']; $password= $_post['Password']; //obtaining user information from DB//PS: Database connection information changed to their own host database user name password$conn = Mysqli_connect ('localhost','Root','Root'); mysqli_select_db ($conn,'Test'); $sql="SELECT * from user where ' username ' = ' $userName '"; $res=mysqli_query ($conn, $sql); $row=Mysqli_fetch_assoc ($res); if($row ['Password'] ==$password) {        //password verification through, set cookies, the user name and password to save on the clientSetcookie ('username', $userName, Time () + -* -* -* -);//set a limitation of one months, one months after this cookie expiresSetcookie ('Password', $password, Time () + -* -* -* -); //finally jump to the Welcome page after loginHeader'Location:welcome.php'."? username= $userName"); }}//use cookies to identify users when re-visitingif(($_cookie['username'] !=NULL) && ($_cookie['Password'] !=NULL) {$userName= $_cookie['username']; $password= $_cookie['Password']; //obtaining user information from DB//PS: Database connection information changed to their own host database user name password$conn = Mysqli_connect ('localhost','Root','Root','Test'); $res= Mysqli_query ($conn,"SELECT * from user where ' username ' = ' $userName '"); $row=Mysqli_fetch_assoc ($res); if($row ['Password'] ==$password) {        //after verification, jump to the Welcome page after loginHeader'Location:welcome.php'."? username= $userName"); }}? >""Method="POST"> <div>User name:<input type="text"Name="username"/>Password:<input type="text"Name="Password"/> <input type="Submit"Value="Login"> </div></form></body>

Jump to the welcome.php code

<?  = $_get['username'];? >   Welcome,<?php Echo $user;? ></body>

In this way, when I first visit cookie.php, I need to enter the user name and password, entered after the jump to welcome.php. Then I close the browser, open the cookie.php again, this time did not ask me to enter the user information, but directly jump to welcome.php, because the cookie information we saved was automatically sent to the server by the browser, Service end processing directly jump to the welcome.php, the server know us! Know that I was the user who landed before, so we kept the stateless HTTP protocol state through cookie technology.
Do it again, I'm sure you'll use a cookie.

Just!!! Just!!! Just!!! Important things to say 3 times, we generally do not put the user name and password in the cookie, because it is not safe, easy to disclose their information, please do not put important information in the cookie. This is just an example of learning cookies.

PHP session control using session in PHP

1. Open session
First we have to open the session, so the first function to learn is
BOOL Session_Start (), this function has no parameters. At the beginning of the PHP file use

Session_Start ();

You can enable new sessions or reuse existing ones.

2. Add Session Data
After the session is opened, in the next process, we can use the $_session variable to access the information. What we need to know is that the $_session variable is a number of arrays. This should be the case when we want to put the information in the session:

$_session[' userName '] = ' Wang ';

3. Reading session data
Reading is simple, as we use arrays, as follows:

$userName = $_session[' userName ');

Of course, you can also $_session[' userName ' to use. and array-like use.
4. Destroying session data
We can use many different ways to destroy session data.
A) unset function
We do this by using similar

unset ($_session[' XXX ');

To destroy the XXX variable in the session. PS: Please don't! Please don't! Please do not unset ($_session), will cause subsequent inability to use $_session this variable!!!
b) Empty array assignment to session variable

$_session = Array ();

As we said before, the $_sessoin variable is the array, and the empty arrays are equivalent to destroying the values in the $_session variables of the current session.
c) session_destory () function
This function destroys all data in the current session and ends the current session. However, the global variables associated with the current session are not reset, and the session cookie is not reset.

5.session extension: Where the default session is stored.
There is such a line in the php.ini configuration file Session.save_handler = files,
Files, which shows that PHP defaults to the file read and write to save the session. So which directory is it? Keep looking. Session.save_path = "/tmp",
There is one in front of this line; , the description is commented, but even then, the default PHP
The session is also stored here in the/tmp directory.

The statement I write to the session is:

$_session[' as ' = ' as ';

To read, the first as represents the $_session[' as ' of the as,|, which represents the data of a string type, 2 represents the number of bytes of the string, and the last double quotation mark is the value as.

PHP Session Management and control

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.