How the Session object in PHP uses the _php technique

Source: Internet
Author: User
Tags md5 session id serialization sessions setcookie file permissions

In PHP development, cookie,session is stored on the server side of the session, relatively secure, and does not have storage-length limitations like cookies. The following is an introduction to the session.

Session and Cookies in PHP

In PHP development, compared with the cookie,session is stored on the server side of the session, relatively secure, and do not like cookies that have storage-length restrictions, this article briefly describes the use of sessions.

Because the session is stored as a text file on the server side, the client is not afraid to modify session content. In fact, the server-side session file, PHP automatically modify the session file permissions, only the system to read and write permissions, and can not be modified through FTP, so much more secure.

For cookies, suppose we want to verify that the user is logged in, you must save the username and password in the cookie (possibly a MD5 encrypted string) and verify each time the page is requested. If the username and password are stored in the database, each time a database query is executed, causing an extra burden to the database. Because we can't just do one validation. Why? Because the information in the client Cookie is likely to be modified. If you store $admin variable to indicate whether the user is logged in, the $admin is true when the login, when false means not logged in, the first time after the verification will $admin equal to true stored in the Cookie, the next time you do not have to verify, this is right? wrong, if someone Forge a $admin variable with a value of true that's not immediately taken. Administrative privileges? Very insecure.

And the session is different, the session is stored on the server side, the remote user can not modify the contents of the session file, so we could simply store a $admin variable to determine whether to log in, the first validation passed after the set $admin value is true, Later to determine if the value is true, if not, go to the login interface, this can reduce a lot of database operations. It also reduces the security of passing passwords every time you verify cookies (session validation only needs to be passed once, if you don't use SSL security protocol). Even if the password is MD5 encrypted, it is very easy to intercept.

Of course, there are many advantages to use the session, such as easy control, can be customized according to user storage, etc. (stored in the database). I don't have much to say here.

Does the session need to be set in php.ini? Generally do not need, because not everyone has to modify the php.ini permissions, the default session of the storage path is the server's system temporary folder, we can customize the store in their own folder, this later I will introduce.

How PHP Creates a session

Begins to describe how to create a session. It's very simple, really.

Start session sessions and create a $admin variable:

Start session session_start (); 
Declares a variable named admin and assigns null values. 
$_session["admin" = null; 
? > 

If you use the session, or if the PHP file calls the session variable, you must start it before calling the session, using the Session_Start () function. Other do not need you to set up, PHP automatically completes the session file creation.

After executing this program, we can go to the system temporary folder to find this session file, general file name like: Sess_4c83638b3b0dbf65583181c2f89168ec, followed by 32-bit encoded random string. Open it with the editor and look at its contents:

 
 

General content Structure:

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 validator, assuming that the database stores the username and MD5 encrypted password:

After form submission ... 
$posts = $_post; 
Clears some blank symbol 
foreach ($posts as $key => $value) 
{ 
$posts [$key] = Trim ($value); 
} 
$password = MD5 ($posts ["Password"]); 
$username = $posts ["username"]; 
$query = "Select ' username ' from ' user ' WHERE ' password ' = ' $password '"; 
Get the result of the query 
$userInfo = $DB->getrow ($query); 
if (!emptyempty ($userInfo)) 
{ 
if ($userInfo ["username"] = = $username) 
{ 
//when validation passes, start session 
session_start (); 
Register login successfully admin variable and assign true 
$_session["admin" = true; 
} 
else 
{ 
die ("User name password Error"); 
} 
else 
{ 
die ("Username password error"); 

We start the session on a page that requires user authentication to determine whether to log in:

Prevent global variables from causing security vulnerabilities 
$admin = false; 
Start the session, this step is essential 
session_start (); 
Determine whether to log in if 
(Isset ($_session["admin")) && $_session["admin"] = = True) 
{ 
echo "You have successfully logged in"; 
} 
else 
{ 
//validation fails, set $_session["admin" to false 
$_session["admin"] = false; 
Die ("You are not authorized to access"); 
} 

Is it simple? Think of $_session as an array stored on the server side, and every variable we register is the key to the array, which is no different than using an array.

What if you want to log out of the system?

<?php 
session_start (); 
This method is to destroy the original registered variable 
unset ($_session["admin")); 
This method is to destroy the entire session file 
Session_destroy (); 
? > 

Can the session set a life cycle like a cookie? Does the session completely discard cookies? I would say that it is most convenient to use a session with a cookie.

How is the session to judge the client user? It is through the session ID to judge, what is the session ID, is that session file name, session ID is randomly generated, so can ensure uniqueness and randomness, to ensure that the session of Ann All. Typically, if the session's lifetime is not set, the session ID is stored in memory, the ID is automatically logged off after the browser is closed, and the session ID is re-register after the page is again requested.

If the client does not disable the cookie, the cookie plays the role of storing the session ID and duration of the sessions at the time of the start. Let's set the lifetime of the session manually:

Session_Start (); 
Save one day 
$lifeTime = * 3600; 
Setcookie (Session_name (), session_id (), time () + $lifeTime, "/"); 
? >

In fact, the session also provides a function session_set_cookie_params (); To set the lifetime of the session, the function must be called before the session_start () function call:

Save one day 
<?php 
$lifeTime = * 3600; 
Session_set_cookie_params ($lifeTime); 
Session_Start (); 
$_session["Admin"] = true; 
? > 

If the client uses IE 6.0, Session_set_cookie_params (); There are some problems with the function setting cookies, so we call the Setcookie function manually to create the cookie.

What if the client disables cookies? No way, all the life cycle is the browser process, as long as the browser closed, request the page again to register session. So how do you pass the session ID? Through the URL or by hiding the form to pass, PHP will automatically send session ID to the URL, such as: http://www.openphp cn/index.php? phpsessid=bba5b2a240a77e5b44cfa01d49cf9669, where the parameter in the URL PHPSESSID is the session ID, we can use $_get to get the value, so that the session ID page passed between.

Save one day 
<?php 
$lifeTime = * 3600; 
Gets the current session name, defaults to PHPSESSID 
$sessionName = Session_name (); 
Get session ID $sessionID = $_get[$sessionName]; 
The session ID 
session_id ($sessionID) obtained using the session_id () setting; 
Session_set_cookie_params ($lifeTime); 
Session_Start (); 
$_session["Admin"] = true; 
? > 

For a virtual host, if all user's session is saved in the System temporary folder, will cause maintenance difficulties, and reduce security, we can manually set the session file save path, Session_save_path () provides such a function. We can point the Session directory to a folder that cannot be accessed through the Web, and of course, the folder must have read-write properties.

<?php 
//Set up a storage directory 
$savePath = "./session_save_dir/"; 
Save one day 
$lifeTime = * 3600; 
Session_save_path ($savePath); Session_set_cookie_params ($lifeTime); 
Session_Start (); 
$_session["Admin"] = true; 
? > 

With Session_set_cookie_params (); function, the Session_save_path () function must also be called before the session_start () function call. We can also store arrays, objects in the session. There is no difference between manipulating an array and manipulating a generic variable, and if you save the object, PHP automatically serializes the object (also called serialization) and then saves it in session. The following example illustrates this point:

<?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 (); 
$_session[' person '] = $person; 
echo "Check here to Output age"; 
? > 
output. PHP 
<?php 
//Set callback function to ensure that the object is rebuilt. 
ini_set (' Unserialize_callback_func ', ' mycallback '); 
function Mycallback ($classname) { 
$classname. ". PHP "; 
} 
Session_Start (); 
$person = $_session["Person"]; 
Output 
$person->output (); 
? > 

When we execute the setage.php file, we call the Setage () method, set the age to 21, and save the State in session (PHP will automatically complete this conversion), and when you go to output.php, you want to output this value, You have to deserialize the object that you just saved, and because you need to instantiate an undefined class at the time of the serialization, we define a later callback function that automatically contains the person. PHP is the class file, so the object is refactored, and the current age value is 21, and then the output () method is invoked to print the value.

To this end, the session in PHP how to use the introduction is finished, I hope to help you learn.

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.