PHP会话

$_SESSION is a special array used to store information across the page requests a user makes during his visit to your website or web application. The most fundamental way to explain what a sessions is like is to imagine the following scenario:

$_SESSION是一个特殊的数组,用于存储用户在访问您的网站或Web应用程序期间发出的整个页面请求中的信息。 解释会话是什么样的最基本方法是想象以下情形:

You are working with an application. You open it, make some changes, and then you close it.

您正在使用一个应用程序。 您打开它,进行一些更改,然后关闭它。

That is a session in it’s simplest form.

这是最简单形式的会话。

The example scenario is reminiscent of the process that happens when using a login system. The process can be extremely complicated or incredibly simple, as long as there is a value that persists between requests. Information stored in the session can be called upon at any time during the open session.

该示例场景使人联想到使用登录系统时发生的过程。 只要在请求之间存在一个值,该过程就可以极其复杂或极其简单。 可以在打开会话期间的任何时间调用会话中存储的信息。

While there may be many users accessing the site at the same time, each with his own session, it’s thanks to unique IDs assigned and managed by PHP for each session that allows each user’s session to be available only to himself. Session information is stored on the server rather than the user’s computer (as cookie data is stored), which makes sessions more secure than traditional cookies for passing information between page requests.

尽管可能有许多用户同时访问该站点,但每个用户都有自己的会话,这要归功于PHP为每个会话分配和管理的唯一ID,从而使每个用户的会话仅对自己可用。 会话信息存储在服务器上而不是用户的计算机上(因为存储了cookie数据),这使会话比传统的cookie更安全,以便在页面请求之间传递信息。

In this article I’ll give you the low down on using sessions in PHP – how to create them, how to destroy them, and how to make sure they remain secure.

在本文中,我将向您介绍如何在PHP中使用会话-如何创建会话,如何销毁它们以及如何确保它们的安全性。

使用会议 (Using Sessions)

Before you can to store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser. To start the session, you call the session_start() function in your first file:

必须先启动PHP的会话处理,然后才能在会话中存储信息。 这是在PHP代码的开头完成的,必须在将任何文本,HTML或JavaScript发送到浏览器之前完成。 要启动会话,请在第一个文件中调用session_start()函数:

<?php
// start them engines!
session_start();
// store session data
$_SESSION["username"] = "Callum";

session_start() starts the session between the user and the server, and allows values stored in $_SESSION to be accessible in other scripts later on.

session_start()启动用户与服务器之间的会话,并允许稍后在其他脚本中访问$_SESSION存储的值。

In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.

在第二个文件中,您再次调用session_start() ,这一次将继续会话,然后可以从$_SESSION检索值。

<?php
// continue the session
session_start();
// retrieve session data
echo "Username = " . $_SESSION["username"];

This example is a very basic demonstration of storing and retrieving data in a session. In the first script, the value “Callum” was associated with the key “username” in the $_SESSION array. In the second script, the information was requested back from the $_SESSION array using the key. $_SESSION allows you to store and retrieve information across the page requests of a user’s active browsing session.

此示例是在会话中存储和检索数据的非常基本的演示。 在第一个脚本中,值“ Callum”与$_SESSION数组中的键“ username”相关联。 在第二个脚本中,使用键从$_SESSION数组中请求信息。 $_SESSION允许您在用户活动浏览会话的页面请求中存储和检索信息。

结束会议 (Ending a Session)

As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information. It is also good practice and will avoid having a huge amount of stale session data sitting on the server.

开始会话与结束会话一样重要。 尽管会话只是存储数据的临时方式,但是在处理潜在的敏感信息时,请务必进行清理以确保最大的安全性,这一点非常重要。 这也是一种很好的做法,可以避免将大量陈旧的会话数据存储在服务器上。

To delete a single session value, you use the unset() function:

要删除单个会话值,请使用unset()函数:

<?php
session_start();
// delete the username value
unset($_SESSION["username"]);

To unset all of the session’s values, you can use the session_unset() function:

要取消设置所有会话值,可以使用session_unset()函数:

<?php
session_start();
// delete all session values
session_unset();

Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.

这两个示例仅影响会话中存储的数据,而不影响会话本身。 如果愿意,您仍然可以在调用其他值后将它们存储到$_SESSION 。 如果您希望完全停止使用会话,例如用户注销,则可以使用session_destroy()函数。

<?php
session_start();
// terminate the session
session_destroy();

I highly recommended that when you are sure you no longer need the session that you destroy it using session_destroy(), rather than just unsetting all of its values with session_unset(). If you just unset all the value, the session itself is still active and malicious code could give those sessions harmful values.

我强烈建议,当你确信你不再需要你用摧毁它的会话session_destroy()而不仅仅是你重置所有的值与session_unset() 如果仅取消设置所有值,则会话本身仍处于活动状态,恶意代码可能为这些会话提供有害的值。

That is sessions in a nutshell, the very basic but very powerful functionality within PHP that provides an elegant solution to the problem of passing data between web pages.

简而言之,即会话是PHP中非常基本但功能非常强大的功能,它提供了一种优雅的解决方案来解决在网页之间传递数据的问题。

会话安全提示 (Session Security Tips)

Despite there simplicity, there are still ways using sessions can go wrong. Here is a quick overview of some security techniques you can use to ensure you are using sessions safely.

尽管简单,但仍有使用会话的方法可能出错。 这是一些安全技术的快速概述,可以用来确保安全使用会话。

会话超时 (Session Time-Outs)

Timing-out sessions is a very important action if you are dealing with users logged in to your website or application. If a user logs in to your site in an Internet café and then leaves the computer and café without logging out, how do you stop the next user on that computer from still having access to the previous user’s session? Well you can use the following code:

如果您要处理登录到您的网站或应用程序的用户,则超时会话是一项非常重要的操作。 如果用户登录到网吧中的站点,然后离开计算机和网吧而不注销,那么如何阻止该计算机上的下一个用户仍然可以访问上一个用户的会话? 好吧,您可以使用以下代码:

<?php
session_start();
// set time-out period (in seconds)
$inactive = 600;

// check to see if $_SESSION["timeout"] is set
if (isset($_SESSION["timeout"])) {
    // calculate the session's "time to live"
    $sessionTTL = time() - $_SESSION["timeout"];
    if ($sessionTTL > $inactive) {
        session_destroy();
        header("Location: /logout.php");
    }
}

$_SESSION["timeout"] = time();

The code ensures that if there is no activity for more than 600 seconds (10 minutes) the request is redirected to the logout page which would successfully log out the user.

该代码确保如果没有活动超过600秒(10分钟),则请求将被重定向到注销页面,该页面将成功注销用户。

重新生成会话ID (Regenerate the Session ID)

The session_regenerate_id() function creates a new unique-ID for to represent the current user’s session. This should be regenerated time any important authentication action is performed, such as logging in or updating user profile data. Giving the sessions a new ID after such actions make your application more secure by reducing the risk of a specific attack known as “Session Hijacking.”

session_regenerate_id()函数创建一个新的唯一ID,用于表示当前用户的会话。 应该在执行任何重要的身份验证操作(例如登录或更新用户配置文件数据)时重新生成该信息。 在采取此类操作后,为会话提供新的ID,可以降低称为“会话劫持”的特定攻击的风险,从而使您的应用程序更安全。

<?php
session_start();

if ($_POST["username"] == "admin" && $_POST["password"] == sha1("password")) {
    $_SESSION["authorized"] = true;
    session_regenerate_id();
}

销毁会话 (Destroy Sessions)

As I previously mentioned, you should use session_destory() once you don’t need to use the session any more. This stops attackers from hijack the stale session, again increasing the session-related security of your web site.

如前所述,一旦不再需要使用会话,就应该使用session_destory() 。 这可以阻止攻击者劫持陈旧的会话,从而再次提高了与网站相关的会话的安全性。

使用永久存储 (Use Permanent Storage)

Use a database to store data at the earliest moment you know the data will be persistent; don’t let it stay as part of the session for too long as this opens it up to possible attack. Really think about whether the data belongs should be stored in $_SESSION because session data is meant to be transient.

在知道数据将是持久性的第一时间,使用数据库存储数据; 不要让它在会话中停留太长时间,因为这会使它容易受到攻击。 真正考虑数据是否应该存储在$_SESSION因为会话数据是临时的。

摘要 (Summary)

In this article you’ve learned what a session is, and how to create, use, and destroy them in PHP. You also saw a few tips to ensure they remain secure. For more information on sessions and session security, please check out these suggested articles and web pages:

在本文中,您了解了什么是会话,以及如何在PHP中创建,使用和销毁它们。 您还看到了一些技巧,以确保它们保持安全。 有关会话和会话安全性的更多信息,请查看以下建议的文章和网页:

Image via Kokhanchikov / Shutterstock

图片来自Kokhanchikov / Shutterstock

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP.

并且,如果您喜欢阅读这篇文章,您会喜欢Learnable的 向大师学习新鲜技能的地方。 会员可以立即访问所有SitePoint的电子书和交互式在线课程,例如Jump Start PHP

Comments on this article are closed. Have a question about PHP? Why not ask it on our forums?

本文的评论已关闭。 对PHP有疑问吗? 为什么不在我们的论坛上提问呢?

翻译自: https://www.sitepoint.com/php-sessions/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值