Home  >  Article  >  Backend Development  >  How to set up, obtain and delete Session in PHP?

How to set up, obtain and delete Session in PHP?

WBOY
WBOYOriginal
2021-10-26 11:59:306018browse

In the previous article, I brought you "How to create, read and delete cookies in PHP? ", which introduces in detail how to create, read and delete cookies in PHP. In this article, we will take a look at setting, obtaining and clearing sessions in PHP. I hope everyone has to help!

How to set up, obtain and delete Session in PHP?

In the previous article, we introduced the cookie used by the client to store user data. In this article, let’s take a look at its use in PHP. Very important session, session is a server-side mechanism, which is also used to save information. Compared with cookies saved on the client, users cannot disable sessions saved on the server side. The same client Every time the client interacts with the server, it does not need to return all cookie values ​​every time. It only needs to return an ID. This ID is generated when the server is accessed for the first time and is unique.

Then let’s take a look at what a session is and how to set, obtain and delete a session

What is a session

session in Chinese means session, which is used to store user-related information, which is similar to cookies, such as user names, personalized settings, etc., but is different from cookies What's interesting is that cookies save data on the client's computer and can be disabled by the user; sessions save data on the server system. The web page is a stateless program connection and cannot record the user's status, so it is particularly important to record the user's relevant information through the session.

When a session is opened, PHP will randomly create a sessionID, and each user's sessionID is unique. This sessionID will be saved on both the client and the server, in the specified directory where cookies will be used on the client; on the server, it will be saved in the form of recalled text in the specified session directory.

Compared with cookies, sessions have many advantages:

Because session data is not passed back and forth between the client and the server, usually the session is still More secure; session can store much more information than cookies; users can disable cookies, but there are ways to make sessions work normally.

After understanding what a session is, let’s take a look at how to open a session.

Opensession

Unlike cookies, cookies can be created directly, but sessions must be started before using them , the purpose is to allow the core program in PHP to preload the session-related built-in environment into memory.

In PHP, the purpose of opening the session can be achieved through the session_start() function. The syntax format of the function session_start() is as follows:

session_start ([array $options = array()])

What needs to be paid attention to Yes:

$options is an optional function and an associative array, and the keys in this array do not need to contain the session. prefix.

The example is as follows:

<?php
    session_start([
        &#39;cookie_lifetime&#39; => 60*60*24,  // 设置 cookie 的有效时间为 1 天
    ]);
    echo &#39;Session ID 为:&#39;.$_COOKIE[&#39;PHPSESSID&#39;];
?>

Output result:

How to set up, obtain and delete Session in PHP?

It should be noted that: call session_start () The function will generate a unique Session ID and save it in the browser's Cookie. The default name is "PHPSESSID". At the same time, a Session file consisting of "sess_" plus Session ID is generated in the local directory to store the data in the Session. The output result is:

How to set up, obtain and delete Session in PHP?

Through the above example , you have learned how to open the session, then let’s take a look at how to set and get the session

Setting and gettingsession

In the above, after starting the session, if you want to use the session variable, you need to set and obtain the data in the session. To complete this, you need to complete it through the $_SESSION array. . Before using $_SESSION, you must first try the session_start() function to open the session.

$_SESSION is an associative array, which has the same meaning as a normal associative array key-value pair. The syntax format for setting Session is as follows:

$_SESSION[名称] = 值;

The example is as follows:

<?php
    session_start();
    $str = &#39;好好学习&#39;;
    $arr = [&#39;Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    foreach ($_SESSION as $key => $value) {
        if(is_array($value)){
            echo $key.&#39;:&#39;;
            print_r($value);
        }else{
            echo $key.&#39; = &#39;.$value.&#39;<br>&#39;;
        }
    }
?>

Output result:

How to set up, obtain and delete Session in PHP?

After running, you need to pay attention to: Save these variables or arrays to $_SESSION, and also save them to a file named by "sess_" and Session ID on the server side. The location of this file can be modified by modifying the php.ini configuration file or using session.save_path configuration.

We have already learned how to open, set and obtain the session. Next, let’s take a look at how to delete the session.

Delete a single session

删除单个session元素需要通过unset()函数,该函数可以释放指定的变量,相当于直接注销掉数组中的元素,他的语法格式如下:

unset(mixed $var [, mixed $...])

其中需要注意的是:

$var 为要释放的变量,unset() 函数可以接收多个参数,参数之间使用,分隔。

实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    unset($_SESSION[&#39;title&#39;]);
    print_r($_SESSION);
?>

输出结果:

How to set up, obtain and delete Session in PHP?

如此便通过unset()函数完成了删除session单个元素了。

删除session多个元素

如果想要一次性删除多个 Session 元素,即一次注销所有的会话变量,可以通过将一个空的数组赋值给 $_SESSION 来实现

实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    $_SESSION = array();
    print_r($_SESSION);
?>

通过将一个空的数组赋值给 $_SESSION 输出结果:

How to set up, obtain and delete Session in PHP?

还有一种方法就是通过session_unset() 函数来释放session中的所有元素,实例如下:

<?php
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    $str = &#39;好好学习&#39;;
    $arr = [&#39;删除 Session&#39;,&#39;$_SESSION&#39;];
    $_SESSION[&#39;study&#39;]  = $str;
    $_SESSION[&#39;study1&#39;]   = &#39;天天向上&#39;;
    $_SESSION[&#39;title&#39;] = $arr;
    echo &#39;定义一个 Session,如下所示:<br>&#39;;
    print_r($_SESSION);
    echo &#39;删除 Session 中名为 title 的元素:<br>&#39;;
    session_unset();
    print_r($_SESSION);
?>

输出结果与上述实例的结果相同,由此我们便通过两种方法可以删除session多个元素了。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of How to set up, obtain and delete Session in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn