Use PHP session of Session to implement user login

  • 2020-06-23 00:04:22
  • OfStack

In contrast to Cookie, Session is a session that is stored on the server side, is relatively secure, and does not have a storage length limit like Cookie. This article briefly introduces the use of Session.

Since Session is stored as a text file on the server side, there is no fear of clients modifying Session content. In fact, on the server side of the Session file, PHP automatically modifies the permissions of the Session file, retaining only the system read and write permissions, and cannot be modified through ftp, so it is much safer.

For Cookie, assuming we want to verify that the user is logged in, we must save the user name and password (possibly an md5 encrypted string) in Cookie and verify it every time the page is requested. If the username and password are stored in the database, one database query is executed each time, placing an unnecessary burden on the database. Because we can't just do one validation. Why is that? Because the information in client Cookie can be modified. If you store $admin to indicate whether the user is logged in, $admin to indicate true and $false to indicate not logged in, store $admin equals true to Cookie after the first pass, so you don't need to authenticate next time, right? No, if someone fakes a $admin variable with the value true, isn't that immediately taking admin privileges? Very unsafe.

And Session is different, Session is stored on the server side, the contents of a remote user can't modify Session file, so we can simply store 1 $admin variable to determine whether to log in, after the validation for the first time through setting $admin value for true, judge whether the value for true later, if not, turn into landing interface, so that can reduce a lot of database operations. It also reduces the insecurity of passing the password every time you want to verify Cookie (Session only needs to be passed once if you are not using SSL security protocol). Even if the password is md5 encrypted, it is easily intercepted.

Of course, there are many advantages to using Session, such as easy control, user-defined storage, and so on (stored in a database). I won't go into more detail here.

Does Session need to be set in ES46en.ES47en? 1 generally not necessary, because not everyone has the right to modify php.ini, default Session storage path is the server system temporary folder, we can customize the storage of their own folder, which I will introduce later.

Start by showing you how to create Session. Very simple, really.
Start the Session session and create a $admin variable:

<?php
//  Start the  Session
session_start();
//  The statement 1 called  admin  , and assigns a null value. 
$_SESSION["admin"] = null;
?> 

If you are using Seesion, or if the PHP file calls the Session variable, you must start it before calling Session, using the session_start() function. You don't need to set anything else. PHP automatically creates Session files.
Execute after this program, we can find the Session file to the system temporary folder, 1 a filename form such as: sess_4c83638b3b0dbf65583181c2f89168ec, behind for the random string is a 32-bit code. Open it with the editor and take a look at its contents:

admin|N;

Generally, the content is structured as follows:

 The variable name | type : The length of the : 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 the form is submitted ...
$posts = $_POST;
//  remove 1 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  Session
session_start();
//  Registered and logged in successfully  admin  Variable, and assign a value  true
$_SESSION["admin"] = true;
} else {
die(" Wrong username and password ");
}
?> 

We launch Session on the page requiring user verification to determine whether to log in:

<?php
//  Prevent global variables from causing security problems 
$admin = false;
//  Starting the session is essential 
session_start();
//  Decide whether to log in 
if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true) {
echo " You have logged in successfully ";
} else {
//  Verification failed, will  $_SESSION["admin"]  Set to  false
$_SESSION["admin"] = false;
die(" You do not have access to ");
}
?> 

Isn't that easy? Just think of $_SESSION as an array stored on the server side. Each variable we register is the key to the array, just like using an array.
What if I want to log out of the system? Destroy Session.

<?php
session_start();
//  The method is to destroy a registered variable 
unset($_SESSION['admin']);
//  This method is to destroy the whole  Session  file 
session_destroy();
?> 

Can Session set the life cycle like Cookie? Do you abandon Cookie altogether with Session? I would say that using Session in combination with Cookie is the most convenient.

How does Session judge the client user? It is determined by Session ID, what is Session ID, which is the file name of the Session file, Session ID is randomly generated, so it can guarantee only 1 and randomness, and ensure the safety of Session. Generally, if the life cycle of Session is not set, Session ID is stored in memory. After closing the browser, the ID is automatically logged out. After re-requesting the page, a new Session ID is registered.

If the client does not disable Cookie, Cookie plays the role of storing the Session ID and Session lifetimes when the Session session is started.
Let's manually set the lifetime of Session:

<?php
session_start();
//  save 1 day 
$lifeTime = 24 * 3600;
setcookie(session_name(), session_id(), time() + $lifeTime, "/");
?> 

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

<?php
//  save 1 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(); Setting up Cookie is a bit of a problem, so we'll manually call the setcookie function to create cookie.

Suppose the client disables Cookie? There is no way, all the life cycle is the browser process, as long as the browser is closed, again request the page to re-register Session. So how do you pass Session ID? Pass through URL or by hidden form, PHP will automatically Session ID sent to URL, URL form such as: http: / / www openphp. cn/index php? PHPSESSID = bba5b2a240a77e5b44cfa01d49cf9669, of which the parameters in the URL PHPSESSID is Session ID, we can use the $_GET to obtain this value, so as to realize Session ID transmission between pages.

<?php
//  save 1 day 
$lifeTime = 24 * 3600;
//  Get the current  Session  Name, default is  PHPSESSID
$sessionName = session_name();
//  achieve  Session ID
$sessionID = $_GET[$sessionName];
//  use  session_id()  Set acquired  Session ID
session_id($sessionID); 
session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?> 

For virtual hosts, if all users of Session are stored in the system temporary folder, it will cause maintenance difficulties and reduce security, we can manually set the save path of the Session file, session_save_path() provides such a function. We can point the Session directory to a folder that cannot be accessed via Web, but must have read-write properties, of course.

<?php
//  Set up the 1 A directory of storage 
$savePath = './session_save_dir/';
//  save 1 day 
$lifeTime = 24 * 3600;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?> 

With session_set_cookie_params (); Like function 1, the session_save_path() function must also be called before the session_start() function call.
We can also store arrays and objects in Session. Manipulating arrays is no different than manipulating variables like Variable 1, while saving objects, PHP automatically serializes objects (also known as serialization) and stores them 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 = new person();
$person->setAge(21);
$_SESSION['person'] = $person;
echo '<a href='output.php'>check here to output age</a>';
?>

output.php

<?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'];
//   The output  21
$person->output();
?>

When we perform setage php file, call the setage () method, set up the age of 21, and to save the state serialized in Session (1 PHP will automatically complete the transformation), when transferred to output. After php, to output the value, must be deserialized just save the object, and because in the deserialized to instantiate a undefined class, so we define the callback function later, The class file person.php is automatically included, so the object is refactored to get the current value of age to 21, and then the output() method is called to output that value.
In addition, we can customize the invocation of Session using the session_set_save_handler function.

Related articles: