Home  >  Article  >  Backend Development  >  Detailed explanation of commonly used functions in Session in PHP

Detailed explanation of commonly used functions in Session in PHP

小云云
小云云Original
2018-03-27 14:22:302361browse

session_start() will create a new session or reuse an existing session. If a session ID is submitted via GET or POST, or using a cookie, the existing session will be reused.

When the session starts automatically or manually through session_start(), PHP internally calls the open and read callback functions of the session manager. The session manager may be the PHP default, or it may be provided by an extension (SQLite or Memcached extension), or it may be a user-defined session manager set by session_set_save_handler(). With existing session data (stored using a special serialization format) returned by the read callback function, PHP will automatically deserialize the data and populate the $_SESSION super global variable.

To use a named session, call the session_name() function before calling the session_start() function.
If the session.use_trans_sid option is enabled, the session_start() function will register an internal output manager that completes URL rewriting.

Note: To use cookie-based sessions, the session_start() function must be called before output starts.

session_unset()

Destroy the current session data. Or$_SESSION = array(); If you want to destroy individual session data, you canunset ($_SESSION['varname']);.

session_destroy()

is different from session_unset() which destroys all session data. session_destroy() destroys the session itself. Once this function comes out, the current session becomes garbage. Wait for the gc mechanism to recycle it. However, it does not reset the global variables associated with the current session, nor does it reset the session cookie. The session data that should be there is still there, but the "identity" has changed. If gc has not recycled it yet, then it can still be read, which of course is not something you want to see, so session_unset()# is often required before session_destroy() ##one time.

If you need to use session variables again, you must call the

session_start() function again. In order to completely destroy the session, such as when the user logs out, the session ID must also be reset. If the session ID is transmitted through a cookie, the setcookie() function also needs to be called to delete the client's session cookie.

The following example is to destroy the data itself:

// 初始化会话。// 如果要使用会话,别忘了现在就调用:session_start();// 重置会话中的所有变量,销毁会话数据$_SESSION = array(); // 或者session_unset() // 如果要清理的更彻底,那么同时删除会话 cookie// 注意:这样不但销毁了会话中的数据,还同时销毁了会话本身if (ini_get("session.use_cookies")) {    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,        $params["path"], $params["domain"],        $params["secure"], $params["httponly"]
    );
}// 最后,销毁会话session_destroy();

Destroy session data

$_SESSION = array() or session_unset(); Destroy the session itselfsession_destroy(); and setcookie(). session_destroy()After execution, the session becomes a garbage session, waiting for recycling by the gc mechanism.

session_commit()

session_commit() is an alias for session_write_close(). As opposed to session_start, this is write and close. That is, save the current session data and close the current session. In order to prevent concurrent session writing, only one PHP script is allowed to operate the session at any time. Therefore, once a script session_start opens the session, the script terminates or calls session_write_close()Before, no other script could use session. By default, the session will be automatically written and closed when the script ends. However, when the script execution time is relatively long, the script will consistently occupy the lock, making other scripts unable to use the session, thus causing many errors. Therefore, the best practice is that for any session variables or data changes (such as $_SESSION[xx] = xxx), you must use session_commit() to save the data and close the session in a timely manner.

session_id ()

session_id() can be used to get/set the current session ID. To easily append a session ID to a URL, you can use the constant SID to get the session name and ID in string format. To put it simply, if you enable the POST/GET method to obtain the session ID, then this parameter can be set through

session.use_trans_sid and can be seen in the URL, and in the script through the global variable SID. Get it directly.

//配置ini_set('session.use_trans_sid', 'sid');//url中表现127.0.0.1?sid=xxxxx//直接获取$sid = SID;

If the value of the

session_id () parameter is specified, the specified value is used as the session ID. The session_id() function must be called before calling the session_start() function. Different session managers have different restrictions on the characters that can be used in session IDs. If there is no current session, an empty string ("") is returned.

There are two points worth noting here:

  • If a cookie is used to transmit the session ID, and the id parameter is specified, the client will be sent to the client after calling session_start() Send a new cookie, regardless of whether the current session ID and the newly specified session ID are the same

  • Before switching the current session ID through session_id ($id), you need to pass

    session_commit( ) to close the previous session, otherwise the current session will remain the same

For more functions, please refer to the PHP official website or manual.

我们在前面的文章里面讲到session的原理和最佳实践,感到意犹未尽。现在再来聊下PHP Session用到的几个相关的函数。

session_start()

session_start() 会创建新会话或者重用现有会话。 如果通过 GET 或者 POST 方式,或者使用 cookie 提交了会话 ID, 则会重用现有会话。

当会话自动开始或者通过 session_start() 手动开始的时候, PHP 内部会调用会话管理器的 open 和 read 回调函数。 会话管理器可能是 PHP 默认的, 也可能是扩展提供的(SQLite 或者 Memcached 扩展), 也可能是通过 session_set_save_handler() 设定的用户自定义会话管理器。 通过 read 回调函数返回的现有会话数据(使用特殊的序列化格式存储), PHP 会自动反序列化数据并且填充 $_SESSION 超级全局变量。

要想使用命名会话,请在调用 session_start() 函数 之前调用 session_name() 函数。  
如果启用了 session.use_trans_sid 选项, session_start() 函数会注册一个内部输出管理器, 该输出管理器完成 URL 重写的工作。

注意:要使用基于 cookie 的会话, 必须在输出开始之前调用 session_start() 函数。

session_unset()

销毁当前会话数据。或者$_SESSION = array(); 如果要销毁个别会话数据,可以unset ($_SESSION['varname']);.

session_destroy()

session_unset()销毁所有会话数据不同,session_destroy()销毁的是会话本身,此函数一出,当前session就变成垃圾了,等待gc机制去回收它。但是它并不会重置当前会话所关联的全局变量, 也不会重置会话 cookie。该有的会话数据还是在,只不过“身份”变了而已。如果gc尚且还没有去回收它,那么它仍然是可以读取到的,这当然是不愿意看到的,因此在session_destroy() 之前往往还要session_unset()一下。

如果需要再次使用会话变量, 必须重新调用 session_start() 函数。 为了彻底销毁会话,比如在用户退出登录的时候,必须同时重置会话 ID。 如果是通过 cookie 方式传送会话 ID 的,那么同时也需要 调用 setcookie() 函数来 删除客户端的会话 cookie。

下面例子是销毁数据本身:

// 初始化会话。// 如果要使用会话,别忘了现在就调用:session_start();// 重置会话中的所有变量,销毁会话数据$_SESSION = array(); // 或者session_unset() // 如果要清理的更彻底,那么同时删除会话 cookie// 注意:这样不但销毁了会话中的数据,还同时销毁了会话本身if (ini_get("session.use_cookies")) {    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,        $params["path"], $params["domain"],        $params["secure"], $params["httponly"]
    );
}// 最后,销毁会话session_destroy();

销毁会话数据$_SESSION = array()session_unset() ;销毁会话本身session_destroy();和setcookie()session_destroy()执行后会话就变成垃圾会话,等待gc机制回收。

session_commit()

session_commit()session_write_close()别称。和session_start相反,这是关闭。即保存当前session数据,并且关闭当前会话。为了防止并发的写session,任何时刻只能允许有一个PHP脚本在操作session,因此,一个脚本一旦session_start打开session,那么在此脚本终止或者调用session_write_close()之前,别的任何脚本都不能使用session。在默认情况下脚本结束时会自动写入和关闭session,但是在脚本执行时间比较长的时候,此脚本就一致占据锁使得别的脚本无法使用session,因此导致许多错误。因此,最佳实践是,任何session变量,数据的更改(如$_SESSION[xx] = xxx),都要及时使用session_commit()保存数据,关闭会话。

session_id ()

session_id() 可以用来获取/设置 当前会话 ID。 为了能够将会话 ID 很方便的附加到 URL 之后, 你可以使用常量 SID 获取以字符串格式表达的会话名称和 ID。简单说,就是如果你开启的是POST/GET方式获取会话ID,那么这个参数可以通过session.use_trans_sid设定并在URL中看得见,而在脚本中通过全局变量SID来直接获取。

//配置ini_set('session.use_trans_sid', 'sid');//url中表现127.0.0.1?sid=xxxxx//直接获取$sid = SID;

如果指定了 session_id () 参数的值, 则使用指定值作为会话 ID。 必须在调用 session_start() 函数之前调用 session_id() 函数。不同的会话管理器对于会话 ID 中可以使用的字符有不同的限制。  如果当前没有会话,则返回空字符串(”“)。

这里有两点值得注意下:

  • 如果使用 cookie 方式传送会话 ID,并且指定了 id 参数, 在调用 session_start() 之后都会向客户端发送新的 cookie, 无论当前的会话 ID 和新指定的会话 ID 是否相同

  • Before switching the current session ID through session_id ($id), you need to close the previous session through session_commit(), otherwise the current session will still be the original one

For more functions, please refer to the PHP official website or manual.

Related recommendations:

Redis shared session detailed explanation

PHP session lock, concurrency, coverage detailed explanation

php modify session survival storage time code sharing

The above is the detailed content of Detailed explanation of commonly used functions in 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