PHP session usage

Source: Internet
Author: User
Compared with cookies in PHP Development, session is stored on the server side, which is relatively secure and has different storage length limits than Cookie, this article briefly introduces the use of session compared to cookies in PHP Development. session is stored on the server side, which is relatively secure and does not have storage length restrictions like cookies. 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

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:


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:

 $ Value) {$ posts [$ key] = trim ($ value);} $ password = md5 ($ posts ["password"]); $ username = $ posts ["username"]; $ query = "Select 'username' FROM 'user' Where 'password' = '$ password '"; // Get the query result $ userInfo = $ DB-> getRow ($ query); if (! Empty ($ userInfo) {if ($ userInfo ["username"] ==$ username) {// after the verification is passed, start 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 for user verification to determine whether to log on: // prevent security risks caused by global variables $ admin = false; // start the SESSION. This step is essential to session_start (); // determine whether to log on to 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.


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:


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:


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? Through URL or hidden form, PHP will automatically send the session ID to the URL. the URL is like: #/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.


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.


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:

 age;   }   function setAge($age) {   $this->age = $age;   }   } ?>

Setage. PHP

 setAge(21);   $_session['person'] = $person;   echo “check here to output age”; ?>

Output. PHP

 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.

Session Details in PHP 2

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.
Generally, variables (server-side variables, the same below) on a page on a website cannot be used on the next page. with session, it is easy. 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 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 d: \ Apache \ php \ local. inc File: class DB_Example extends DB_ SQL {var $ Host = "localhost"; // mysql Database Host name var $ Database = "test "; // database name var $ User = "root"; // database username var $ Password = "1234567"; // database username and 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:

  <?php   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:

 <?php $sess->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:

<? Php page_open (array ("sess" => "Test _ Session"); $ sess-> register ("welcome"); // registers the variable $ welcome, note that you do not need to add $ welcome = "Hello, PHP world! ";...... Page_close ();?>

Page 2:

<? Php page_open (); // start session echo $ welcome; // display the $ welcome page_close () defined on the first page; // Save 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:

<?php     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:

<? Session_start ()?> <Html> <body> <? $ Welcome = "hello world! "; Session_register (" welcome "); // register the $ welcome variable. Note that there is no $ symbol if (session_is_registered (" welcome ")) // check whether the $ welcome variable registers the echo "welcome variable! "; Else echo" welcome variable is not registered yet! ";?> </Body> 

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 function 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 function session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");?>

Test code customized by session:

<? Php ...... If ($ handler = "dbm") include ("session_dbm.php"); // The interface 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 to echo "Dear user, welcome";} else {// If you have not logged on to echo "please register first! ";}?>

User logout:

   <?     session_destroy();     ……     ?>

How can I run multiple sessions concurrently?
Question: I wrote an invoicing system for my unit and found that multiple users need to be allowed to access a php application at the same time. The originally designed static and unique session ID causes Data confusion. In this way, it is imperative to dynamically generate a unique session ID.
The solution is simple: I use the php file name + timestamp as the unique session ID, so that every session in my program will be unique and will not be confused.
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();

Program notes:
Use mysessionname as the unique sessionname between pages to pass variables. 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: 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.