Php session basic knowledge

Source: Internet
Author: User
Tags cron script drupal

In php, session is a global variable on the server that can be transferred between pages. Therefore, session is often used for Logon verification by server-side User Members. session Security is also very high, next I will introduce the basic php session knowledge.

What do you think about sessions? I don't know whether you have studied it. Today, Dana's php training teacher wants to share some content in this area with you. I hope you will like it.

How long is the session lifecycle?

1. When the browser ends, its lifecycle also ends, but the file still exists in/tmp/(sess _???)
 
2. The sessionID will be re-allocated when you re-open the browser next time. If you use session_id () to bring back the previous ID, the sess _???, Retrieve all the previously set parameters
 
3. You can modify the remaining time of the session file in PHP. ini.
 
Session. gc_maxlifetime = 1440; after this number of seconds, stored
Data will be seen as 'garbage' and
Cleaned up by the gc process
The default value is 1440 seconds, 24 minutes
 
Storage path issues when using session
 
Check the session settings in php. ini.
 
[Session]
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
Path where data files are stored

By default, it is stored in the/tmp directory, which may not be true !!! It is best to change to your php installation path, such as c:/php


Thoroughly understand the php 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 enable garbage collection because the session is stored in the file,
The garbage collection of PHP itself is invalid, and the collection of sessions is to delete files. This probability is determined based on the configuration of php. ini,
However, some systems use session. gc_probability = 0, which means the probability is 0, but garbage collection is implemented through the cron script.

Session. gc_probability = 1
Session. gc_divisor = 1000
Session. gc_maxlifetime = 1440 // The default expiration time is 24 minutes.
// The probability is session. gc_probability/session. gc_divisor. Result 1/1000,
// It is not recommended to set too small because session garbage collection requires checking whether each file has expired.
Session. save_path = // It seems that different systems have different default values. One of the following settings is "N;/path"
// This is a random Hierarchical Storage. In this case, garbage collection does not work and you need to write your own scripts.

2. The session checks whether $ _ COOKIE [session_name ()]; session_name () returns the COOKIE key value for saving session_id,
This value can be found in php. ini.

Session. name = PHPSESSID // default value: PHPSESSID

3. If it does not exist, a session_id will be generated, and the generated session_id will be passed to the client as the COOKIE value.
The following COOKIE operation is performed. Note that the setcookie () operation is performed in this step, and the COOKIE is sent in the header,
No output is available before. PHP has another function session_regenerate_id (). If this function is used, no output is available before.

Setcookie (session_name (),
Session_id (),
Session. cookie_lifetime, // The default value is 0.
Session. cookie_path, // The default '/' is valid in both the current program and directory.
Session. cookie_domain, // null by default
)

4. If session_id =$ _ COOKIE [session_name];
Go to the folder specified by session. save_path to find the file named 'sess _ '. session_id.
Read the file content deserialization and put it in $ _ SESSION.
* 2. assign a value to $ _ SESSION
For example, if a new value $ _ SESSION ['test'] = 'blah' is added, this $ _ SESSION will only be maintained in the memory. When the script execution ends,
Write the $ _ SESSION value to the folder specified by session_id, and then close related resources. In this phase, you may change the session_id,
For example, destroy an old session_id and generate a new session_id. Half of it is used for custom session operations and role conversion,
For example, if an anonymous user of Drupal. Drupal has a SESSION, the new session_id needs to be used after logon.

If (isset ($ _ COOKIE [session_name ()]) {
Setcookie (session_name (), '', time ()-42000, '/'); // The old session cookie expires.
}
Session_regenerate_id (); // This step generates a new session_id
// Session_id () returns a new value.

3. Write SESSION
At the end of the script, the SESSION write operation will be executed to write the $ _ SESSION value to the file named session_id, which may already exist,
You may need to create a new file.
* 4. Destroy the SESSION
The COOKIE sent by the SESSION is generally an instant COOKIE, which is stored in the memory. It will expire only when the browser is closed. If the COOKIE needs to be forcibly expired,
For example, to log out, 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,...); // run the command before logging out.
O 2. usset ($ _ SESSION); // This will delete all $ _ SESSION data. After refreshing, a COOKIE is sent, but no data exists.
O 3. session_destroy (); // This function is more thorough. Delete $ _ SESSION to delete the session file and session_id.

When the browser is not closed, refresh the page again. Cookies are sent from both 2 and 3, but no data is found.

2. session. save_handler = user

The custom session processing mechanism is more intuitive.
* Session_set_save_handler ('open', 'close', 'read', 'write', 'deststroy', 'gc ');
1. session_start (),
Execute open ($ save_path, $ session_name) to open the session operation handle.
$ Save_path is session. save_path when session. save_handler = files,
However, if you do not use these two parameters, TRUE is returned directly.

Execute read ($ id) to read data from it. // this parameter is automatically passed as session_id () and can be operated through this value.
* 2. Script Execution ends
Execute write ($ id, $ sess_data) // two parameters, which are very simple.
* 3. If the user needs session_destroy ()
Run destroy first.

An example:

The Code is as follows: Copy code

// Called during SESSION Initialization
Function open ($ save_path, $ session_name)
{
Global $ sess_save_path;
$ Sess_save_path = $ save_path;
Return (true );
}

// Called when disabled
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 );
}
// Execute the write operation before the script execution ends.
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 ));
}

Function gc ($ maxlifetime)
{
Global $ sess_save_path;

Foreach (glob ("$ sess_save_path/sess _ *") as $ filename ){
If (filemtime ($ filename) + $ maxlifetime <time ()){
@ Unlink ($ filename );
}
}
Return true;
}


Example

Before you store user information in a PHP Session, you must start the session.

Note: The session_start () function must be located before the

The Code is as follows: Copy code

<?

Php session_start ();?>

<Html>
<Body>

</Body>
</Html>

The above code registers a user's session with the server so that you can start to save the user information and assign a UID to the user session.
Store Session Variables
The correct method for storing and retrieving session variables is to use the PHP $ _ SESSION variable:

The Code is as follows: Copy code

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

<Html>
<Body>

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

</Body>
</Html>

Output:

Pageviews = 1

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.