Some basic knowledge of session in PHP

Source: Internet
Author: User
Tags garbage collection ini php session setcookie cron script drupal

What do you think of the session? I do not know if you have studied, today the PHP training teachers want to share some of the content of this, I hope you can enjoy.

How long is the session life cycle ?

1 The end of the browser's lifecycle also ends at the same time, but the file still exists in/tmp/(Sess_???)

2 The next time you open the browser will redistribute SessionID, if you use session_id () to bring back the previous ID, you will read the remaining in/tmp Sess_???, get back all the parameters you've set before

3 can modify the duration of the session file in PHP.ini

Session.gc_maxlifetime = 1440; After this number of seconds, stored
Data would be seen as ' garbage ' and
Cleaned up by the GC process
The default is 1440 seconds, 24 minutes.

Storage path problems with session attention

Look at the settings for the session in PHP.ini.

Session.save_handler = files; Handler used to Store/retrieve data
Session.save_path =/tmp; Argument passed to Save_handler
In the case of files, this is the
path where data files are stored

Default is stored in/tmp directory, this directory may not really have AH!!! It's best to change to your PHP installation path, such as c:/php

Thoroughly understand PHP's session mechanism 1.session.save_handler = files

    * 1. Session_Start ()
         1 session_start () Is the beginning of the session mechanism, it has a certain probability to open garbage collection, because the session is stored in the file,
PHP itself garbage collection is invalid, the session of the recycling is to delete the file, the probability is based on the configuration of the php.ini decision,
But some systems are session.gc_probability = 0, which means that the probability is 0, but the cron script is used to implement garbage collection.

session.gc_probability = 1
Session.gc_divisor = 1000
Session.gc_maxlifetime = 1440//expiration default 24 minutes
Probability is session.gc_probability/session.gc_divisor result 1/1000,
It is not recommended to set too small, because the session garbage collection, you need to check whether each file expires.
Session.save_path =//As if different systems default, one setting is "N;/path"
This is random tiered storage, this kind of word, garbage collection will not work, need to write their own script

2. The session will determine whether there is currently a $_cookie[session_name ()];session_name () that returns the COOKIE key value of the saved session_id.
This value can be found from php.ini = PHPSESSID//default value PHPSESSID

3. If not present generates a session_id, then passes the generated session_id as the value of the cookie to the client.
Equivalent to performing the following cookie operation, note that this step performs the Setcookie () operation, the cookie is sent in the header header,
There is no output before this, PHP has another function session_regenerate_id () If you use this function, this can not have output before.

Setcookie (Session_name (),

session_id (),

session.cookie_lifetime,//Default 0

session.cookie_path,//default '/' current program and directory are valid

session.cookie_domain,//default is empty


         4. If there is so session_id = $_cookie[session_name];
            then go to Session.save_path's designated folder to find the name ' Sess_ '. session_id () file.
            Read the contents of the file deserialized, and then put it into $_session
     * 2. Assign a value to the $_session
      For example add a new value $_session[' test ' = ' blah '; then this $_session will only be maintained in memory, When the script finishes,
writes the value of the $_session to the folder specified by session_id, and then closes the associated resource .      this phase is likely to perform a change session_ ID,
such as destroying an old session_id and generating a new session_id. Half used in custom session actions, role transitions,
For example, the anonymous user of Drupal.drupal has a session, and when it logs in, it needs to swap with the new session_id

        if (Isset ($_cookie[session_name ())) {
           Setcookie (Session_name (), ', Time ()-42000, '/')//old session cookie expires
        session_regenerate_id ();// This step generates a new session_id
      //session_id () returns a new value

3. Write Session operation
The session write operation is performed at the end of the script, and the $_session value is written to the session_id named file and may already exist.
You may need to create a new file.
* 4. Destroy session
The cookie that the session sends out usually belongs to the instant cookie, saves in the memory, when the browser closes, only then expires, if needs the artificial force expiration,
For example, to exit the login, rather than close the browser, you need to destroy the session in the code, there are many methods,
o 1. Setcookie (Session_name (), session_id (), Time ()-8000000, ...); /exit Pre-Logon execution
o 2. Usset ($_session)//This will delete all the $_session data, after refreshing, there is a cookie passed, but no data.
o 3. Session_destroy ()//This role is more thorough, delete $_session Delete session file, and session_id

When the browser is not closed, refresh again, 2 and 3 will have a cookie passed, but no data found

2.session.save_handler = user

User-defined session processing mechanism, more intuitive
* Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destroy ', ' GC ');
1.session_start (),
Executes open ($save _path, $session _name) opens the session action handle
$save _path is session.save_path in the case of Session.save_handler = files,
But if the user is determined, this two parameters will not be used, directly return True

The execution of Read ($id) reads from the data.//This parameter is automatically passed is session_id (), which can be manipulated by this value.
* 2. End of script execution
Execute write ($id, $sess _data)//two parameters, very simple
* 3. If the user needs Session_destroy ()
Execute the destroy first. In the 2nd step of the execution

A practical example:

The code is as follows Copy Code

Called when the session is initialized
function open ($save _path, $session _name)
Global $sess _save_path;
$sess _save_path = $save _path;
return (true);

Called when it is closed
function Close ()
return (true);

      function Read ($id)
         Global $sess _save_path;
        $sess _file = "$sess _save_path/sess_$id";
        Return (String) @file_get_contents ($sess _file);
     //script execution is completed, write operations
      function Write ($id, $sess _ Data)
        echo "SDFSF";
         global $sess _save_path;

$sess _file = "$sess _save_path/sess_$id";
if ($fp = @fopen ($sess _file, "W")) {
$return = fwrite ($fp, $sess _data);
Fclose ($FP);
return $return;
} else {
return (false);


function Destroy ($ID)
Global $sess _save_path;

$sess _file = "$sess _save_path/sess_$id";
Return (@unlink ($sess _file));

Global $sess _save_path;

foreach (Glob ("$sess _save_path/sess_*") as $filename) {
if (Filemtime ($filename) + $maxlifetime < time ()) {
@unlink ($filename);
return true;


PHP Session before you store the user information in the PHP sessions, you must first start the conversation.

Note: the Session_Start () function must precede the

The code is as follows Copy Code


PHP session_start ();?>



The code above registers a user's session with the server so that you can start saving user information while assigning a UID to the user's session.
Store Session Variable
The correct way to store and retrieve session variables is to use PHP $_session variables:

The code is as follows Copy Code

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


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




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: 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.