Using PHP session to implement user login function _php Tutorial

Source: Internet
Author: User
Tags php session setcookie
Compared to the cookie,session is stored on the server side of the session, relatively safe, and does not have the same storage length as the Cookie limit, this article briefly introduces the use of the session.

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

For a cookie, if we want to verify that the user is logged in, we must save the user name and password in the cookie (possibly the MD5 encrypted string) and verify it each time the page is requested. If the user name and password are stored in the database, a database query is executed once each time, which creates an unnecessary burden on the database. Because we can't just do one Test at a time. Why is it? 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, $admin is true when the login, false indicates not logged in, after the first pass the verification will be $admin equal to true stored in the Cookie, next time will not be verified, so right? Wrong, if someone forged a $admin variable with a value of true that is not immediately taken to the administrative rights? It's not very safe.

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 setting $admin value is true, Later to determine whether the value is true, if not, into the landing interface, so that you can reduce a lot of database operations. It can also reduce the security of passing passwords every time a Cookie is validated (Session validation needs to be passed only once if you are not using the SSL security protocol). Even if the password is MD5 encrypted, it is easy to intercept.

Of course, the use of the Session has many advantages, such as easy to control, according to user-defined storage, etc. (stored in the database). I'm not going to say much 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 Temp folder, we can customize to store in their own folder, this later I will introduce.

Start by describing how to create a Session. It's very simple, really.
Start session sessions and create a $admin variable:
Copy CodeThe code is as follows:
Start Session
Session_Start ();
Declare a variable named admin and assign a null value.
$_session["admin"] = null;
?>

If you use Seesion, or if the PHP file is to invoke the session variable, you must start it before calling the session and use the Session_Start () function. Others do not need you to set up, PHP automatically complete the Session file creation.
After the implementation of this program, we can go to the system Temp folder to find the Session file, the general file name such as: Sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it with an editor and look at its contents:
Copy CodeThe code is as follows:
admin| N

Generally this is the structure of this content:
Copy CodeThe code is 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 user name and MD5 encrypted password:
login.php
Copy CodeThe code is as follows:
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 ' and ' username ' = ' $username '";
Get query Results
$userInfo = $DB->getrow ($query);
if (!empty ($userInfo)) {
When the validation passes, start the Session
Session_Start ();
Register the login successful admin variable and assign the value true
$_session["Admin"] = true;
} else {
Die ("User name password error");
}
?>

We start the Session on a page that requires user authentication to determine whether to log in:
Copy CodeThe code is as follows:
Prevent global variables from causing security risks
$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 landed";
} else {
Validation failed with $_session["admin" set to False
$_session["admin"] = false;
Die ("You are not authorized to access");
}
?>

Isn't it simple? Consider $_session as an array stored on the server side, and every variable we register is the key to the array, not the same as using the array.
What if I want to log out of the system? The Session can be destroyed.
Copy CodeThe code is as follows:
Session_Start ();
This method destroys a variable that was originally registered
unset ($_session[' admin ');
This method is to destroy the entire Session file
Session_destroy ();
?>

Can the Session set the life cycle like a Cookie? Does the Session abandon the Cookie altogether? I would say that it is most convenient to use a Session with a Cookie.

How does the Session determine the client user? It is determined by the session ID, what is the session ID, is the file name of the session file, session ID is randomly generated, so to ensure uniqueness and randomness, to ensure that the session security. In general, if the lifetime of the session is not set, the session ID is stored in memory, the ID is automatically logged off after the browser is closed, and a session ID is re-registered after the page is re-requested.

If the client does not disable cookies, the cookie plays the role of storing the session ID and session lifetime when the session is started.
let's set the lifetime of the Session manually:
Copy CodeThe code is as follows:
Session_Start ();
Save the 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 Session, the function must be called before the session_start () function call:
Copy CodeThe code is as follows:
Save the 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 cookie, so let's call the Setcookie function manually to create a cookie.

What if the client disables cookies? No way, all the life cycle is the browser process, as long as the browser is closed, re-request the page again to register the Session. So how do you pass the Session ID? via a URL or by a hidden form, PHP automatically sends the Session ID to the URL, such as: http://www.openphp.cn/index.php? Phpsessid= bba5b2a240a77e5b44cfa01d49cf9669, where the parameter Phpsessid in the URL is the session ID, we can use the $_get to get the value, so that the session ID between the page pass.
Copy CodeThe code is as follows:
Save the day
$lifeTime = 24 * 3600;
Gets the current Session name, which defaults to 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 saved in the System temporary folder, will make maintenance difficult, 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 by the Web, and of course the folder must have read/write properties.
Copy CodeThe code is as follows:
Set up a storage directory
$savePath = './session_save_dir/';
Save the 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 general variable, and if you save the object, PHP automatically serializes the object (also called serialization) and then saves it in the Session. This is illustrated in the following example:
person.php
Copy CodeThe code is as follows:
Class Person {
var $age;
function output () {
Echo $this->age;
}
function Setage ($age) {
$this->age = $age;
}
}
?>

setage.php
Copy CodeThe code is as follows:
Session_Start ();
Require_once ' person.php ';
$person = new Person ();
$person->setage (21);
$_session[' person '] = $person;
Echo ' Check here for output age ';
?>

output.php
Copy CodeThe code is as follows:
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 21
$person->output ();
?>

When we execute the setage.php file, we call the Setage () method, set the age to 21, and save the State in the Session (PHP will automatically complete the conversion), when the switch to output.php, to output this value, You have to deserialize the object you just saved, and because you need to instantiate an undefined class at the time of the deserialization, we define a later callback function that automatically contains the Person.php class file, so the object is refactored, takes the current age value to 21, and then calls output () method to output the value.
In addition, we can use the Session_set_save_handler function to customize the way the session is called.

http://www.bkjia.com/PHPjc/327932.html www.bkjia.com true http://www.bkjia.com/PHPjc/327932.html techarticle compared to the cookie,session is stored on the server side of the session, relatively safe, and does not have the same storage length as the Cookie limit, this article briefly introduces the use of the session. Due to the Sessi ...

  • Related Article

    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.