Phpsession usage analysis

Source: Internet
Author: User
Both Session and Cookie are used to save user information, but the difference is that the Cookie is the stored client, and the Session is saved on the server. Compared with cookies, sessions are stored on the server, which is relatively secure. Unlike cookies, Session persistence and cookies are used to store user information, however, the difference is that the Cookie is saved on the client, and the Session is saved on the server. Compared with cookies, sessions are stored on the server side. they are relatively secure and have different storage length limits than cookies. Session refers to the time that a user spends browsing a website from entering the website to closing the browser. From the above definition, we can see that Session is actually a specific concept of time.

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.

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:

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


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

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


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:

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:


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


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

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

Class person
{
Var $ age;
Function output (){
Echo $ this-> age;
}

Function setAge ($ age ){
$ This-> age = $ age;
}
}
?>
Setage. php
Session_start ();
Require_once "person. php ";
$ Person = new person ();
$ Person-> setAge (21 );
$ _ SESSION ['person '] = $ person;
Echo "check here to output age ";
?>
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 execute setage. in the php file, the setage () method is called, the age is set to 21, and the status is serialized and saved in the Session (PHP will automatically complete this conversion ), when it is switched to output. after php, to output this value, you must deserialize the saved object. because an undefined class needs to be instantiated during deserialization, we have defined the callback function in the future, automatically contains person. php class file. Therefore, the object is restructured and the current age value is 21. then, the output () method is called to output the value.

In addition, we can use the session_set_save_handler function to customize the Session call method.

Generally, variables (server variables) on a page on a website cannot be used on the next page. with session, information can be saved on multiple webpages, transfer value, Session can not even pass value across sites. The variables registered in the session can be used as global variables. In this way, the session can be used for user identity authentication, Program Status record, and parameter transfer between pages.

In PHP3, how does one implement the session?

Php3 itself does not implement the session function. we can only implement it using other methods. The most famous one is phplib. Phplib's most basic functions include user authentication, Session management, permission and database abstraction. The following describes how to use phplib to implement a session.

1. install phplib first (the environment is win2000 + php3.0.16 + Apache1.3.12 + phplib7.2c + mysql3.23.21 for win32)

First, unbind phplib, which contains a "php" directory, and copy the directory to the Apache installation directory. For example, if Apache is installed under the d: \ Apache Directory, copy the "php" directory to the d: \ Apache Directory, and copy the pages directory of the phplib Directory (excluding the directory itself) copy the file and directory to d: \ Apache \ htdocs.

The phplib class library needs to be initialized based on the system. you may need to modify the local. inc file, which contains some basic parameters that can be modified based on the actual situation of your machine.

Change a program in the d: \ Apache \ php \ prepend. php file as follows:
If (! Isset ($ _ PHPLIB) or! Is_array ($ _ PHPLIB )){
$ _ PHPLIB ["libdir"] = "d:/Apache/php/"; // path of the php directory under phplib
}

Modify the d: \ Apache \ php \ local. inc file:
Class DB_Example extends DB_ SQL {
Var $ Host = "localhost"; // Host name of the mysql database
Var $ Database = "test"; // Database name
Var $ User = "root"; // database username
Var $ Password = "1234567"; // database user Password
}

Finally, the initial table is generated based on the create_database.mysql file in the stuff subdirectory under the phplib directory.

For every page using phplib, you must first find the class library file necessary to run phplib. the auto_prepend variable is set in ini. phplib contains a prepend. php file, and specify auto_prepend as "d:/Apache/php/prepend. php "(with quotation marks), the pages will automatically contain the phplib class library. we can also add the directory where the phplib class library is located to the include variable so that you can find these files.

2. call the page_open () function.

On every page that uses phplib, you must first call the page_open function for initialization. for example:

Page_open (array ("sess" => "Test_Session "));
?>



The array variable (sess) is used to initialize some State-saving objects. Note that phplib built-in names (sess) must be used, which are defined in local. inc ..

Because phplib uses Cookies to save status information, the page_open () function must be called before the page content is output to the browser. The php script should end with page_close (), which will write the relevant status data back to the database; otherwise, the variable will be lost.

3. specific use.

Register a variable and use it on the subsequent page until the session ends. Method:

Register ("varname");?>

Note that varname is not a variable value, but a variable name. you can specify a variable name before assigning a value. You can change the value of a variable on a page. Then, when you access the variable on the page, you will get the changed value. Variable types are diverse. they can be a string, a number, and an array. For example:

Page 1:

Page_open (array ("sess" => "Test _ Session "));
$ Sess-> register ("welcome"); // register the variable $ welcome. do not add $
$ Welcome = "Hello, PHP world! ";
......
Page_close ();
?>

Page 2:

Page_open (); // start session
Echo $ welcome; // display the $ welcome defined on the first page
Page_close (); // Save the status information
?>

After registering a variable, when the page finally calls the page_close () function, each session variable will be written back to the database. If you forget to call the page_close () function, the variable will not be written back to the database, and unpredictable consequences will occur. When the variable is used and no longer needed, you can call the following function to delete the variable:

Page_open (array ("sess" => "Test _ Session "));
......
$ Sess-> unregister ("variable_name ");
......
Page_close ();
?>

In PHP4, how does one implement session?

The session id of php4 is saved by cookies and stored by the file system (by default). Therefore, its session variables cannot store objects. You can also save the session in the database.

There are many session functions in php4 (for details, refer to php. ini configuration). generally, we only need to call three functions: sesssion_start (), session_register (), and session_is_registered ().

Call the session_start () function at the beginning of each page of the session. for example:



$ Welcome = "hello world! ";
Session_register ("welcome"); // register the $ welcome variable. Note that the $ symbol does not exist.
If (session_is_registered ("welcome") // check whether the $ welcome variable is registered
Echo "welcome variable already registered! ";
Else
Echo "welcome variable is not registered yet! ";
?>


Customization of session processing in php4

We need to expand six functions:
Sess_open ($ sess_path, $ session_name );
This function is called by the session handler for initialization.
The $ sess_path parameter corresponds to the session. save_path option in the php. ini file.
The $ session_name parameter corresponds to the session. name option in php. ini.

Sess_close ();
This function is called when the page ends and the session processing program needs to be closed.

Sess_read ($ key );
When the session handler reads the specified session key value ($ key), this function retrieves and returns session data identified as $ key. (Note: serialization is a technology that stores variables or objects in files when the program ends or needs to be stored. it is different from the method that only saves data when the next program runs or needs to be transferred to the memory .)

Sess_write ($ key, $ val );
This function is called when the session handler needs to save data, which often occurs when the program ends. It stores the data in the location where the sess_read ($ key) function can be used for retrieval next time.

Sess_destroy ($ key );
This function is required to destroy the session. It is responsible for deleting sessions and clearing the environment.

Sess_gc ($ maxlifetime );
This function is responsible for clearing fragments. In this case, it is responsible for deleting outdated session data. Session handlers occasionally call them.

The custom program can use the mysql database or DBM file to save session data, depending on the specific situation. To use mysql for support, perform the following steps:

First, create a sessions database in mysql and create a sessions table:

Mysql> Create DATABASE sessions;
Mysql> GRANT select, insert, update, delete ON sessions. * TO phpsession @ localhost
-> Identified by 'phpsession ';
Mysql> Create TABLE sessions (
-> Sesskey char (32) not null,
-> Expiry int (11) unsigned not null,
-> Value text not null,
-> Primary key (sesskey)
-> );

Next, modify the $ SESS_DB * variable in the session_mysql.php file to match the database settings on your machine:

$ SESS_DBHOST = "localhost";/* database host name */
$ SESS_DBNAME = "sessions";/* database name */
$ SESS_DBUSER = "phpsession";/* database username */
$ SESS_DBPASS = "phpsession";/* database password */
$ SESS_DBH = "";
$ SESS_LIFE = get_cfg_var ("session. gc_maxlifetime ");

...... // Custom functions

Session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc ");
?>

Custom interfaces for using dbm files:

$ SESS_DBM = "";
$ SESS_LIFE = get_cfg_var ("session. gc_maxlifetime ");

...... // Custom functions

Session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc ");
?>

Test code customized by session:

......
If ($ handler = "dbm") include ("session_dbm.php"); // the interface used
Elseif ($ handler = "mysql") include ("session_mysql.php ");
Else ......

Session_start ();
Session_register ("count ");
......
?>

In identity authentication, how does one apply Session?

Session can be used for user authentication:

Verify that the user is legal:

Session_start ();
...... // Verification process
Session_register ("reguser ");
?>

On the other page, check whether the user is logged on.

Session_start ();
If (isset ($ reguser) & $ reguser! = "") {// If you have logged on
Echo "Dear user, welcome ";
} Else {// If you have not logged on
Echo "please register first! ";
}
?>

User logout:

Session_destroy ();
......
?>

How can I run multiple sessions concurrently?

Question: I am writing an entry for my unit. in this way, every session in my program will be yours, and it will be no longer confusing.

I will publish my source code below to help you solve the same problem.

// Start a PHP session to preserve variables.
If (empty ($ mysessionname )){
$ Micro = microtime ();
$ Micro = str_replace ("", "", $ micro); // strip out the blanks
$ Micro = str_replace (".", "", $ micro); // strip out the periods
$ Mysessionname = "po_maint". $ micro;
}
Session_name ($ mysessionname );
Session_start ();

Mysessionname is the only sessionname passing variable between pages. if you use this name, you must make a small change to the above program. Mysessionname cannot be the internal variable name of the session, because it already exists before the session starts. Mysessionname cannot be stored as a cookie, because multiple sessions will certainly overwrite the original cookie file. You can use an implicit form field to save it. In this way, no problem occurs.

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.