Detailed introduction to session usage in PHP

Source: Internet
Author: User
Tags function prototype garbage collection php session sessions

Before you store the user information in the PHP session, you must first start the conversation.

Note: the Session_Start () function must precede the

The code is as follows Copy Code


<?php session_start ();?>

<body>

</body>

Face code registers a user's session with the server so that you can begin 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

<?php
Session_Start ();
Store session Data
$_session[' views ']=1;
?>

<body>

<?php
Retrieve session data
echo "pageviews=". $_session[' views '];
?>

</body>

Output:

Pageviews=1 in the following example, we created a simple page-view counter. The Isset () function detects whether the "views" variable has been set. If you have set the "views" variable, we accumulate the counter. If "views" does not exist, we create the "views" variable and set it to 1:

The code is as follows Copy Code

<?php
Session_Start ();

if (isset ($_session[' views '))
$_session[' views ']=$_session[' views ']+1;

Else
$_session[' views ']=1;
echo "views=". $_session[' views '];
?>


There are 11 functions in the PHP processing session, and we'll talk about several functions we'll use.

1, Session_Start

function function: Start a session or return a session that already exists.

Function prototype: Boolean session_start (void);

Return Value: Boolean value

Function Description: This function has no parameters and the return value is true. It is best to place this function first, and there is no output before it, otherwise it will alarm, such as: Warning:cannot send session cache Limiter-headers already sent (output started At/us R/local/apache/htdocs/cga/member/1.php:2) in/usr/local/apache/htdocs/cga/member/1.php on line 3

2, Session_register

function function: Register a new variable as session variable

Function prototype: Boolean Session_register (string name);

Return value: Boolean value.

Function Description: This function is to add a variable in the global variable to the current session, the parameter name is the name of the variable you want to join, and success returns the logical value TRUE. You can use the form of $_session[name] or $http_session_vars[name] to take a value or assign a value.

3, session_is_registered

function function: Checks whether a variable is registered as a session variable.

Function prototype: Boobean session_is_registered (string name);

Return Value: Boolean value

Function Description: This function checks whether the specified variable is registered in the current session, and the parameter name is the variable name to check. Success returns the logical value TRUE.

4, Session_unregister

function function: Deletes a registered variable.

Function prototype: Boolean Session_session_unregister (string name);

Return Value: Boolean value

Function Description: This function deletes the variables in the global variable in the current session. The parameter name is the name of the variable you want to delete, and success returns TRUE.

5, Session_destroy

function function: Ends the current session and empties all resources in the session.

Function Prototype: Boolean session destroy (void);

Return value: Boolean value.

Function Description: This function ends the current session, this function has no arguments, and the return value is True

The functions described above will be used, but there are also some functions about the session:

6, Session_encode

function function: sesssion information encoding

Function prototype: string session_encode (void);

return value: String

Function Description: The returned string contains the names and values of the variables in the global variable in the form of: A|s:12: "It is a test"; C|s:4: "Lala"; A is the variable name s:12 represents the value of variable a "it is a test length is a semicolon between 12 variables"; Separated.

7, Session_decode

function function: sesssion information decoding

Function prototype: Boolean Session_decode (String data)

Return Value: Boolean value

Function Description: This function can decode session information, success returns the logical value TRUE

8, Session_name

function function: Accessing the current session name

Function prototype: Boolean session_name (string [name]);

return value: String

Function Description: This function can get or reset the name of the current session. Without the parameter name, the current session name is obtained, plus the parameter indicates that the session name is set to the parameter name

9, session_id

function function: Accessing the current session identification number

Function prototype: Boolean session_id (string [id]);

return value: String

Function Description: This function can get or reset the identification number of the current session. The absence of a parameter ID means that only the identification number of the current session is obtained, plus the parameter indicates that the session's identification number is set to the newly specified ID

10, Session_unset

function function: Deletes all registered variables.

Function prototype: void Session_unset (void)

Return Value: Boolean value

Function Description: This function is different from Session_destroy, it does not end the session. Just like using a function session_unregister to log off all of the session variables

Where is the


session information saved in which file directory and what type of data can be used to hold   1.SESSION information stored?                                                                                        

The code is as follows Copy Code
<?php
Session_Start ();
$_session[' name ']= ' Marcofly ';
?>

Session defaults are saved to the C:windows emp directory, but the save path to the session can be changed by modifying the Session.save_path value in php.ini.

such as: Session.save_path = "D:/wamp/tmp"


--------------------------------------------------------------------------------

After executing the code, it will be in the D:/wamp/tmp directory, add a file named: sess_*** file, after opening, the contents are as follows: Name|s:8: "Marcofly";

File Content Explanation:

Name:key

S: Save type is a string

8: String length

Marcofly:value

What type of data can the session hold?

As the previous example shows, sessions can hold strings, not only that, the session can also hold integers (int), Boolean (bool), arrays (array), and the session can save objects

Let's take a look at a simple example:

The code is as follows Copy Code


<?php
Session_Start ();
$_session[' name ']= ' marcofly ';//String
$_session[' int ']= ' 10 ';//integral type
$_session[' bool ']=true;//boolean type
$_session[' array ']=array (' name ' => ' marcofly ', ' age ' => ' 23 ');//Array
Class test{
Public $msg;
Public Function __construct () {
$this->msg= "Hello World";
}
}
$obj =new test ();
$_session[' obj ']= $obj;//Object
?>

The results are as follows:

Name|s:8: "Marcofly";

Int|s:2: "10";

Bool|b:1;

Array|a:2:{s:4: "Name"; S:8: "Marcofly"; s:3: "Age"; S:2: "23";}

obj| O:4: "Test": 1:{s:3: "MSG"; s:11: "Hello World";}

About the use of the session I have told a lot before, we can look at ha.

Garbage collection mechanism of session
Session.gc_maxlifetime

Session.gc_probability

Session.gc_divisor

Session.gc_divisor and session.gc_probability together define the probability of starting a GC (garbage collection garbage collection) process when each session is initialized. This probability is calculated by Gc_probability/gc_divisor. For example, 1/100 means that the GC process is initiated in a 1% probability per request. Session.gc_divisor defaults to 100.

For example: Session.gc_maxlifetime=30,session.gc_divisor=1000,session.gc_probability=1, which means that every 1000 users call Session_Start (), It's going to be a garbage collection mechanism that deletes the session files that are useless on the disk.

Note: Generally for some large portal sites, it is recommended to increase the session.gc_divisor, reduce overhead

Next, I'll show you how to configure the GC (garbage collection) process by using an example!

Modify the following information by configuring the php.ini file:

Session.gc_maxlifetime = 60//When the session file has not been accessed after 60s, the session file will be treated as "junk file" and be cleaned up while the GC (garbage collection) process is called.
session.gc_probability = 1000
Because the probability of the GC process being invoked is computed by gc_probability/gc_divisor, I change the session.gc_probability to 1000, and session.gc_divisor by default is 1000. The GC process is invoked every time the Session_Start () function is executed.

Below I pass the screenshot simple explanation below:

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


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.