Getting Started with PHP sessions (session)

Source: Internet
Author: User
Tags array getting started with php ini log session id php class php file file permissions
Session

Comparing the cookie,session is stored on the server side of the session, relatively secure, and does not have the storage length limit as cookies do, 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, then? 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 to indicate that the login is not logged in, false, the first time after the verification will be $admin equal to true stored in the Cookie, the next time you do not have to verify, this right? Wrong, if someone faked a $admin variable with a value of true does that not immediately take the administrative authority? It's very unsafe.

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 session need to be set in php.ini? Generally do not need, because not everyone has the right to modify the php.ini, the default session of the storage path is the server's system temporary folder, we can customize the store in their own folder, which I will introduce later.

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

Start session sessions and create a $admin variable:

<?php
//Start session
Session_Start();
//Declare a variable named admin and assign null value.
$_session["admin" = null;
?>

If you use Seesion, or if the PHP file calls the session variable, you must start it before calling the session and use 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:

admin| N

This is generally the structure of this content:

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:

login.php

<?php

After form submission ...
$posts = $_post;
Clear some whitespace 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 '";
Get query Results
$userInfo = $DB->getrow ($query);

if (!empty ($userInfo))
{
if ($userInfo ["username"] = = $username)
{
When validation passes, start session
Session_Start ();
Register login successfully admin variable and assign a value of True
$_session["Admin"] = true;
}
Else
{
Die ("Username password error");
}
}
Else
{
Die ("Username password error");
}

?>

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

<?php

//Prevent global variables from causing security risks
$admin = False;

//Start session, this step is essential
Session_Start();

//Judge whether to log in
if (Isset ($_session["admin")) && $_session["admin"] = = True)
{
echo "You've landed successfully";
}
Else
{
//validation failed, set $_session["admin" to False
$_session["admin" = False;
Die ("You are not authorized to access");
}

?>

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

What if you want to log out of the system? The session can be destroyed.

<?php

Session_Start();
//This method is to destroy a variable that was originally registered
unset ($_session["admin"));

//This method is to destroy the entire session file
Session_destroy();

?>

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

How does the session judge the client user? It is through the session ID to judge, what is the session ID, that is the file name of the session file, session ID is randomly generated, so can ensure uniqueness and randomness, to ensure the security session. 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:

<?php

Session_Start ();
Save 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 lifetime of the sessions, which must be called before the session_start () function call:

<?php

//Save one day
$lifeTime = 3600;
Session_set_cookie_params ($lifeTime);
Session_Start();
$_session["Admin"] = True;

?>

If the client uses IE 6.0, session_set_cookie_params () , the function setting cookie has some problems, 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 through the hidden form to pass, PHP will automatically send the session ID to the URL, such as the URL form: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 to implement the session ID page Transfer between the surfaces.

<?php

//Save one day
$lifeTime = * 3600;
//Get the current session name, default to Phpsessid
$sessionName = Session_name();
Get Session ID
$sessionID = $_get[$sessionName];
//The session ID obtained using the session_id () setting
session_id ($sessionID);

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;

?>

like the session_set_cookie_params () function, thesession_save_path () function must also be in session_start () called before a 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:

person.php

<?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 = newperson();
$person->setage ();
$_session[' person '] = $person;
echo "<a href= ' output ' >check to output age</a>";

?>

output.php

<?

     //set the callback function to ensure that the object is rebuilt.
    ini_set (' Unserialize_callback_func ', ' mycallback '     function mycallback ($classname          include_once $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 must deserialize the object that you just saved. Because we need to instantiate an undefined class at the time of the serialization, we define a later callback function that automatically contains the Person.php class file, so the object is refactored and gets the current age value of 21, and then calls output () method to output the value.

Alternatively, we can use the session_set_save_handler function to customize how the session is called.



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.