Use the PHP session (sessions) to achieve user login function

Source: Internet
Author: User
Tags ini md5 session id php class php file php session serialization file permissions

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 in the form of 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 the 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 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 the landing, the first time the validation passed after the set $admin value is true, after the judge If the value is true, if not, go to the login interface, which can reduce the number 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 using the session, such as easy control, can be customized by 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.


starts session sessions and creates a $admin variable:


Copy Code code as follows:


<?php


//Start session


session_start ();


//declares a variable named admin and assigns null values.


$_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.


execution of 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:


Copy Code code as follows:


admin| N


generally this content is such a structure:


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


login.php


Copy Code code as follows:


<?php


//Form Submit ...


$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 ' and ' username ' = ' $username '";


//Get query Results


$userInfo = $DB->getrow ($query);


if (!empty ($userInfo)) {


//When validation passes, start session


session_start ();


//Register login successfully admin variable and assign true


$_session["admin" = true;


} else {


die ("Username password error");


}


?>


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


Copy Code code as follows:


<?php


//Prevent global variables from causing security risks


$admin = false;


//Start session, this step is essential


session_start ();


//Judge whether to login


if (isset ($_session["admin")) && $_session["admin"] = = True) {


echo "You have successfully landed";


} else {


//Authentication failed, set $_session["admin" to false


$_session["admin" = false;


die ("You are not entitled to access");


}


?>

is
very 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.


Copy Code code as follows:


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





session is how to 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 a cookie is not disabled by the client, the cookie plays the role of storing the session ID and sessions lifetime at the time of initiating the conversation.


us to set the lifetime of the session manually:
Copy code code as follows:


<?php


session_start ();


//Save one day


$lifeTime = 24 * 3600;


Setcookie (Session_name (), session_id (), time () + $lifeTime, "/");


?>


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


Copy Code code as follows:


<?php


//Save 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 (); 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 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 the $_get to get the value, so that the session ID page passed between.


Copy Code code as follows:


<?php


//Save one day


$lifeTime = 24 * 3600;


//Get current session name, default is PHPSESSID


$sessionName = Session_name ();


//Get session ID


$sessionID = $_get[$sessionName];


//session ID obtained using the session_id () setting


session_id ($sessionID);


Session_set_cookie_params ($lifeTime);


session_start ();


$_session[' admin ' = true;


?>


for the virtual host, if all the user's session is stored in the system temporary folder, will be difficult to maintain, and reduce security, we can manually set the session file save path, Session_save_path () on the provision of 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.


Copy Code code as follows:


<?php


//Set up a storage directory


$savePath = './session_save_dir/';


//Save one day


$lifeTime = 24 * 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:


person.php
Copy code code as follows:


<?php


class Person {


var $age;


function Output () {


Echo $this->age;


}


function Setage ($age) {


$this->age = $age;


}


}


?>


setage.php
Copy code code as follows:


<?php


session_start ();


require_once ' person.php ';


$person = new Person ();


$person->setage (21);


$_session[' person ' = $person;


Echo ' <a href= ' output.php ' >check to output age</a> ';


?>


output.php
Copy Code code as follows:


<?php


//sets 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 21


$person->output ();


?>


when we execute the setage.php file, we call the Setage () method, set the age of 21, and save the state after the session (PHP will automatically complete this conversion), when you go to output.php, to output this value, you must Serializes 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 the current age value is 21, and then the output () method is invoked to print the value.


In addition, 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.