Compared to Cookie, Session is a server-side session, relatively secure, and unlike Cookie, there is no storage length limit. This article briefly introduces the use of Session.

Since Session is stored on the server side as text files, there is no fear of clients modifying Session content. In fact, for the Session files on the server side, PHP automatically modifies the file permissions, leaving only system read and write permissions, and they cannot be modified via FTP, so it is much safer.

For Cookie, suppose we want to verify whether a user is logged in. We must store the username and password (possibly an md5-encrypted string) in the Cookie, and verify them on every page request. If the username and password are stored in the database, a database query must be executed each time, causing unnecessary burden on the database. Because we cannot verify only once. Why? Because the information in the client Cookie can be modified. Suppose you store an $admin variable to indicate whether the user is logged in. When $admin is true, it means logged in; when false, it means not logged in. After the first verification passes, you store $admin equal to true in the Cookie, and next time no verification is needed. Is that correct? Wrong. If someone forges an $admin variable with a value of true, wouldn't they immediately gain administrative rights? It is very unsafe.

Session is different. Session is stored on the server side, so remote users cannot modify the contents of Session files. Therefore, we can simply store an $admin variable to determine whether the user is logged in. After the first verification passes, set $admin to true. Later, check whether this value is true; if not, redirect to the login page. This can reduce many database operations. It also reduces the insecurity of transmitting passwords each time for Cookie verification (Session verification only needs to be transmitted once, if you do not use the SSL security protocol). Even if the password is md5-encrypted, it can easily be intercepted.

Of course, using Session has many other advantages, such as easy control and the ability to customize storage according to the user (e.g., storing in a database). I won't go into detail here.

Does Session need to be configured in php.ini? Generally no, because not everyone has permission to modify php.ini. The default storage path for Session is the server's system temporary folder. We can customize it to be stored in our own folder, which I will introduce later.

Now let's introduce how to create a Session. It is very simple, really.

Start a Session and create an $admin variable:

Example

<?php
// Start Session
session_start();
// Declare a variable named admin and assign an empty value.
$_SESSION["admin"] = null;
?>

If you use Session, or if this PHP file needs to call Session variables, you must start it before calling Session, using the session_start() function. You don't need to configure anything else; PHP automatically creates the Session file.

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

admin|N;

Generally, the content has the following structure:

variable name|type:length:value;

Each variable is separated by a semicolon. Some parts can be omitted, such as length and type.

Let's look at the verification program, assuming the database stores the username and the md5-encrypted password:

login.php file code

<?php
// After the form is submitted...
$posts = $_POST;
// Remove some whitespace characters
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 the query result
$userInfo = $DB->getRow($query);

if (!empty($userInfo)) {
    // Start Session after verification passes
    session_start();
    // Register the admin variable for successful login and assign true
    $_SESSION["admin"] = true;
} else {
    die("Invalid username or password");
}
?>

On pages that require user authentication, we start Session and determine whether the user is logged in:

Example

<?php
// Prevent security risks caused by global variables
$admin = false;
// Start the session, this step is essential
session_start();
// Determine whether the user is logged in
if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true) {
    echo "You have successfully logged in";
} else {
    // Verification failed, set $_SESSION["admin"] to false
    $_SESSION["admin"] = false;
    die("You do not have permission to access");
}
?>

Isn't it simple? Just think of $_SESSION as an array stored on the server side. Every variable we register is a key of the array, just like using an array.

What if you want to log out of the system? Just destroy the Session.

Example

<?php
session_start();
// This method destroys a previously registered variable
unset($_SESSION['admin']);
// This method destroys the entire Session file
session_destroy();
?>

Can Session set a lifetime like Cookie? With Session, should we completely abandon Cookie? I would say that using Session in combination with Cookie is the most convenient.

How does Session identify the client user? It is identified by the Session ID. What is a Session ID? It is the file name of that Session file. The Session ID is randomly generated, thus ensuring uniqueness and randomness, and ensuring the security of the Session. Generally, if the Session lifetime is not set, the Session ID is stored in memory. After closing the browser, the ID is automatically logged out, and after requesting the page again, a new Session ID is registered.

If the client does not disable Cookie, Cookie plays the role of storing the Session ID and Session lifetime when the Session session is started.

Let's manually set the Session lifetime:

Example

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

Actually, Session also provides a function session_set_cookie_params(); to set the Session lifetime. This function must be called before the session_start() function is called:

Example

<?php
// Save for one day
$lifeTime = 24 * 3600;
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>

If the client uses IE 6.0, the session_set_cookie_params(); function may have some problems setting Cookie, so we still manually call the setcookie function to create the cookie.

What if the client disables Cookie? There is no way around it; all lifetimes are tied to the browser process. As soon as the browser is closed, you must re-register the Session when requesting the page again. So how do you pass the Session ID? Pass it through the URL or through a hidden form. PHP automatically sends the Session ID to the URL. The URL looks like: http://www.test.cn/index.php?PHPSESSID= bba5b2a240a77e5b44cfa01d49cf9669, where the parameter PHPSESSID in the URL is the Session ID. We can use $_GET to obtain that value, thereby passing the Session ID between pages.

Example

<?php
// Save for one day
$lifeTime = 24 * 3600;
// Get the current Session name, default is PHPSESSID
$sessionName = session_name();
// Get the Session ID
$sessionID = $_GET[$sessionName];
// Use session_id() to set the obtained Session ID
session_id($sessionID);

session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?>

For virtual hosts, if all users' Sessions are saved in the system temporary folder, it will cause difficulties in maintenance and reduce security. We can manually set the save path for Session files. session_save_path() provides such a function. We can point the Session storage directory to a folder that cannot be accessed via the Web. Of course, the folder must have read and write permissions.

Example

<?php
// Set a storage directory
$savePath = './session_save_dir/';
// Save for one day
$lifeTime = 24 * 3600;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?>

Like the session_set_cookie_params(); function, the session_save_path() function must also be called before the session_start() function.

We can also store arrays and objects in Session. Manipulating arrays is no different from manipulating ordinary variables, but when saving objects, PHP will automatically serialize (also called serialization) the objects and then save them in Session. The following example illustrates this:

person.php file code

<?php
class person {
    var $age;
    function output() {
        echo $this->age;
    }
    function setAge($age) {
        $this->age = $age;
    }
}
?>

setage.php file code

<?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 file code

<?php
// Set the callback function to ensure 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 serialize this state before saving it to Session (PHP will automatically complete this conversion). When we go to output.php, to output this value, we must deserialize the object saved just now. And because deserialization requires instantiating an undefined class, we defined a callback function to automatically include the person.php class file, so the object is reconstructed, and the current age value is obtained as 21, then the output() method is called to output that value.

In addition, we can also use the session_set_save_handler function to customize the way Session is called.

Original address: https://www.cnblogs.com/happyforev1/articles/1645916.html