PHP Session Mechanism---the basic use of sessions

Source: Internet
Author: User
Tags php session

PHP Session Mechanism---the basic use of sessions

1, thinking: After logging into the site, you can get the user information on each page

(1) The use of hyperlinks to pass the user name, this is too cumbersome, not recommended.

(2) Use the database, each open a page to query the user Information table, so that the page loading speed is slow, the user experience becomes worse.

(3) Using cookies, the server stores the user information to the client's cookie after the login is successful. This has drawbacks:

① security is poor, the user information is stored locally, it is easy to be found by others.

② server every time you open a Web page, all through the network to read user information from the client, so waste bandwidth, when a lot of users, each user open a lot of pages, will waste huge bandwidth.

(4) The solution: Session

2,session Technology

Session is a server-side technology, using this technology, the server can create a unique session file for each user's browser, because the session is exclusive to the user's browser, so when users access the server's Web resources, The data can be placed in the respective session, and when the user accesses other Web resources on the server, other Web resources are then fetched from the user's session to serve the user.

3. Save session information

index1.php

123 <?phpsession_start(); // 初始化session$_SESSION[‘name‘] = "zhangsan"//保存某个session信息

index2.php

123 <?phpsession_start();echo$_SESSION[‘name‘];

Run index1.php in the Web page before running the index2.php page output:

4,session can save multiple data types

The session not only saves strings, but also preserves integers, booleans, arrays, objects, and so on.

index1.php

12345678910111213141516171819202122 <?phpsession_start(); // 初始化session$_SESSION[‘name‘] = "zhangsan"//保存某个session信息$_SESSION[‘age‘] = 100;$_SESSION[‘isBoy‘] = true;$arr1array("北京","小明","hello");$_SESSION[‘arr1‘] = $arr1;classDog{    private$name;    private$age;    private$intro;    function__construct($name,$age,$intro){        $this->name = $name;        $this->age = $age;        $this->intro = $intro;    }}$dog1newDog("大黄",2,"很听话");$_SESSION[‘dog1‘] = $dog1;

index2.php

1234567 <?phpsession_start();foreach($_SESSIONas$key=>$value){    echo$key.":";    var_dump($value);    echo"<br/>";}

Run index1.php in the Web page before running the index2.php page output:

5. Get session Information

(1) Get all session directly

(2) Access by key

A) get a variable directly

b) Get array

c) Gets the object, the session can not save the object when the information of the class can not be saved, so in obtaining the object, it is necessary to declare the class first. You can refer to this file separately as a file, storing and reading the session.

The 6,session update is to re-save the session value based on the key value.

7, Session deletion

(1) Specify to delete a key value pair in session

(2) Delete all session

8,session data Default time is 1440s (24 minutes), can be modified in php.ini, Session.gc_maxlifetime = 1440. Session file storage path can be modified, you can change the Sesion file storage path by modifying php.ini, Session.save_path = "tcp://127.0.0.1:11211".

9,session before use, first initialization, session_start (), this is more troublesome, you can set the session in PHP.ini automatic initialization, Session.auto_start = 0 (This method is not recommended).

10, when the browser accesses the page a.php, the server generates a session file, stores it in the server, sends session_id to the browser, and the browser saves it to a cookie. When the browser accesses b.php again, the session_id is sent to the server from the cookie, and the server obtains the corresponding session content according to SESSION_ID.

Question: How do I use the session if the browser disables cookies?

With URL rewriting, url rewriting is divided into manual and automatic. Automatic rewrite URL is to configure php.ini, open transparent SID, other programs do not change, automatic rewrite URL is not safe, not recommended.

To turn on transparent SIDS, the php.ini that need to be modified are:

Session.use_trans_sid = 1//change from 0 to 1

session.use_only_cookies = 0//Whether only using cookies to save session value This parameter is 1 o'clock, the above mechanism is invalid.

session.use_cookies = 0//Set whether the client uses cookies to hold session values the value of this parameter does not affect the mechanism above. This is not a change.

Manual mode:

index1.php

123456 <?phpsession_start();$_SESSION[‘name‘] = "zhangsan";$_SESSION[‘age‘] = 100;echo‘session save succes! click <a href="index2.php?‘.SID.‘">here</a> to see SID<br/>‘;

index2.php

1234567 <?php if ( $_get [ "Phpsessid" ]) {       session_id ( $_get [ "Phpsessid" ]); } session_start (); echo  session_id (). ' <br/> ' echo  $_session [ ' name ' ];

In the automatic mode, the PHPSESSID parameter is added automatically after the URL, so the SID can be removed in the index1.php, index2.php unchanged.

index1.php

123456 <?phpsession_start();$_SESSION[‘name‘] = "zhangsan";$_SESSION[‘age‘] = 100;echo‘session save succes! click <a href="index2.php">here</a> to see SID<br/>‘;

Configuration of session and Cookie in 11,php.ini

(1) session.use_trans_sid = 0, when turned on, the default is to add session_name=session_id after each URL.

(2) session.save_path= "C:/mysession", Save_path is the session file in the server storage path.

(3) Session.gc_maxlifetime = 1440,session default maximum life cycle, when session file is not accessed after 1440s, then the session is considered "junk file" and waiting for GC (garbage collection) Process calls are cleared; session.gc_probability=1;session.gc_divisor=1000; These two parameters are set reasonably according to the size of the website. Whenever a session is initialized, there is a gc_probability/gc_divisor probability to perform a garbage collection.

I open three sessions, then create three corresponding session files, when each file is not called in 30 seconds, it will be considered as "junk file", wait until the GC process calls, "junk file" will be unlink, Because I have previously modified the php.ini configuration file, the GC is called the probability of change to hundred percent, so next, if I re-use any browser to refresh the next page, the three session file, there should be only one left.

(4) Session.cookie_lifetime, in seconds, specifies the lifetime of the cookie sent to the browser, and a value of 0 means "until the browser is closed." The default is 0. This is similar to the program in Setcookie ("name", "Zhangsan", Time () +60);

PHP Session Mechanism---the basic use of sessions

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.