PHP session (session time setting) getting started

Source: Internet
Author: User
Tags php session

Compared with cookies in PHP development, Session is stored on the server, which is relatively secure and has a storage length limit unlike Cookie. This article briefly introduces the use of Session.

The Session is stored on the server as a text file, so the client is not afraid to modify the Session content. In fact, in the Session file on the server side, PHP automatically modifies the Session file permissions, only retaining the system read and write permissions, and cannot be modified through ftp, which is much safer. PHPChina open source community portal k % W % e2CY

For Cookie, if we want to verify whether the user logs in, we must save the user name and password (which may be the md5 encrypted string) in the Cookie and perform verification on each request page. If the user name and password are stored in the database, a database query is executed every time, causing extra burden on the database. Because we cannot perform only one verification. Why? Because the information in the client Cookie may be modified. If you store the $ admin variable to indicate whether the user has logged on, $ admin indicates logging on when it is set to true, and false indicates not logging on, after the first verification is passed, $ admin equals true is stored in the Cookie, so no verification is required next time. Is this correct? Wrong. If someone spoofs a $ admin variable with the value true, isn't the administrator privilege immediately obtained? Very insecure.

The Session is different. The Session is stored on the server, and remote users cannot modify the content of the Session file. Therefore, we can simply store a $ admin variable to determine whether to log on, after the first verification is passed, set $ admin to true, and then judge whether the value is true. If not, transfer it to the login interface, which can reduce a lot of database operations. In addition, it can reduce the security of passing passwords to verify cookies every time (Session verification only needs to be passed once, if you do not use the SSL Security Protocol ). Even if the password is encrypted with md5, it is easily intercepted.

Of course, Session has many advantages, such as easy control and user-defined storage (stored in the database ). I will not talk about it here.

Does Session need to be set in php. ini? Generally, this is not required because not everyone has modified php. ini permission. The default Session storage path is the temporary system folder of the server. We can customize it to be stored in our own folder. I will introduce it later.

This topic describes how to create a Session. Very simple, really.

Start the Session and create a $ admin variable:

<? Php
// Start the Session
Session_start ();
// Declare a variable named admin and assign a null value.
$ _ SESSION ["admin"] = null;
?>

If you use Seesion or the PHP file needs to call the Session variable, you must start the Session before calling it and use the session_start () function. PHP automatically creates the Session file.

After executing this program, we can find the Session file in the temporary folder of the system. The file name is generally sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it in the editor and check its content:

Admin | N;

Generally, the content is structured as follows:

Variable name | type: Length: value;

Separate each variable with a semicolon. Some can be omitted, such as length and type.

Let's take a look at the verification program. Assume that the database stores the user name and the md5 encrypted password:

<? Php
// After the form is submitted...
$ Posts =$ _ POST;
// Clear some blank symbols
Foreach ($ posts as $ key => $ value)
{
$ Posts [$ key] = trim ($ value );
}
$ Password = md5 ($ posts ["password"]);
$ Username = $ posts ["username"];
$ Query = "SELECT 'username' FROM 'user' WHERE 'Password' = $ password ";
// Obtain the query result
$ UserInfo = $ DB-> getRow ($ query );
If (! Empty ($ userInfo ))
{
If ($ userInfo ["username"] = $ username)
{
// After the verification is passed, start the Session
Session_start ();
// Register the logon admin variable and assign the value true.
$ _ SESSION ["admin"] = true;
}
Else
{
Die ("incorrect user name and password ");
}
}
Else
{
Die ("incorrect user name and password ");
}

We start the Session on the page that requires user verification to determine whether to log on:

<? Php
// Prevent security risks caused by global variables
$ Admin = false;
// Start the session. This step is required.
Session_start ();
// Determine whether to log on
If (isset ($ _ SESSION ["admin"]) & $ _ SESSION ["admin"] = true)
{
Echo "you have successfully logged on ";
}
Else
{
// Verification Failed. Set $ _ SESSION ["admin"] to false
$ _ SESSION ["admin"] = false;
Die ("You are not authorized to access ");
}
?>

Is it easy? Consider $ _ SESSION as an array stored on the server. Every variable we register is an array key, which is no different from the array used.

What if I want to log out of the system? Destroy the Session.

<? Php
Session_start ();
// This method destroys a previously registered variable.
Unset ($ _ SESSION ["admin"]);
// This method destroys the entire Session file.
Session_destroy ();
>

Can a Session set a lifecycle like a Cookie? Does Session discard cookies? I would like to say that using Session with cookies is the most convenient.

How does the Session determine the client user? It is determined by the Session ID. What is the Session ID is the name of the Session file, and the Session ID is randomly generated. Therefore, the uniqueness and randomness can be ensured to ensure the security of the Session. Generally, if the Session life cycle is not set, the Session ID is stored in the memory. When the browser is closed, the ID is automatically deregistered. After the page is requested again, a Session ID is re-registered.

If the client does not disable the Cookie, the Cookie plays the role of storing the Session ID and Session lifetime when the Session is started.

Let's manually set the Session lifetime:

<? Php
Session_start ();
// Save for one day
$ LifeTime = 24*3600;
Setcookie (session_name (), session_id (), time () + $ lifeTime ,"/");
?>

In fact, the Session also provides a function session_set_cookie_params (); To set the Session lifetime. This function must be called before the session_start () function is called:

<? Php
// Save for one day
$ LifeTime = 24*3600;
Session_set_cookie_params ($ lifeTime );
Session_start ();
$ _ SESSION ["admin"] = true;
?>

If the client uses IE 6.0, session_set_cookie_params (); the function sets the Cookie. Therefore, we need to manually call the setcookie function to create the cookie.

What if the client disables cookies? No way. All life cycles are browser processes. You only need to close the browser and request the page to register the Session again. So how to pass the Session ID? By passing through a URL or by hiding a form, PHP will automatically send the Session ID to the URL, the URL is like: http://www.openphp.cn/index.php? PHPSESSID = bba5b2a240a77e5b44cfa01d49cf9669. the PHPSESSID parameter in the URL is the Session ID. We can use $ _ GET to obtain this value, so that the Session ID can be transmitted between pages.

<? Php
// Save for one day
$ LifeTime = 24*3600;
// Obtain the current Session name. The default value is PHPSESSID.
$ SessionName = session_name ();
// Obtain the Session ID
$ SessionID = $ _ GET [$ sessionName];
// Use session_id () to set the Session ID
Session_id ($ sessionID );
Session_set_cookie_params ($ lifeTime );
Session_start ();
$ _ SESSION ["admin"] = true;
?>

For a VM, if all users' sessions are saved in a temporary system folder, maintenance is difficult and security is reduced. You can manually set the Session file storage path, session_save_path () provides such a function. We can direct the Session directory to a folder that cannot be accessed through the Web. Of course, this folder must have the read/write attribute.

<? Php
// Set a storage directory
$ SavePath = "./session_save_dir /";
// Save for one day
$ LifeTime = 24*3600;
Session_save_path ($ savePath );
Session_set_cookie_params ($ lifeTime );
Session_start ();
$ _ SESSION ["admin"] = true;
?>

Like the session_set_cookie_params (); function, the session_save_path () function must also be called before the session_start () function is called.

We can also store arrays and objects in sessions. There is no difference between an Operation Array and an operation variable. If you save an object, PHP will automatically serialize the object (also called serialization) and save it in the Session. The following example illustrates this:

<? Php
Class person
{
Var $ age;
Function output (){
Echo $ this-> age;
}
Function setAge ($ age ){
$ This-> age = $ age;
}
}
?>
Setage. php
<? Php
Session_start ();
Require_once "person. php ";
$ Person = new person ();
$ Person-> setAge (21 );
$ _ SESSION [person] = $ person;
Echo "<a href = output> check here to output age </a> ";
?>
Output. php
<?
// Set the callback function to re-build the object.
Ini_set (unserialize_callback_func, mycallback );
Function mycallback ($ classname ){
$ Classname. ". php ";
}
Session_start ();
$ Person = $ _ SESSION ["person"];
// Output 21
$ Person-> output ();
?>

When we

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.