Php 简明教程
PHP - Sessions
Web 会话是从用户与服务器建立连接到连接终止之间的时间。与 cookies 一起,会话变量使数据可以在整个网站的各个页面中访问。
A web session is the time duration between the time a user establishes connection with a server and the time the connection is terminated. Along with the cookies, the session variables make the data accessible across the various pages of an entire website.
在会话期间,网站维护有关用户操作和偏好的信息。会话数据填充在超全局关联数组 $_SESSION 中。
During a session, the website maintains information about the user’s actions and preferences. The session data is populated in a superglobal associative array $_SESSION.
要在 PHP 中启动一个新会话,你需要调用 session_start() 函数。
To start a new session in PHP, you need to call the session_start() function.
Starting a Session
为了启用对会话数据的访问,必须调用 session_start() 函数。 session_start() 基于通过 GET 或 POST 请求或通过 cookie 传递的会话标识符,创建一个会话或恢复当前会话。
In order to enable access to session data, session_start() function must be invoked. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
session_start(array $options = []): bool
如果会话成功启动,此函数返回 true ;否则返回 false 。
This function returns true if a session was successfully started, otherwise false.
PHP 首先为该特定会话创建一个唯一标识符,该标识符是由 32 个十六进制数字组成的随机字符串。
PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers.
session_id() 函数设置或检索唯一会话 ID。
The session_id() function sets or retrieves a unique session ID.
session_id(?string $id = null): string|false
如果未给定 $id 参数,PHP 将生成一个随机会话 ID。你也可以指定自己的 ID。该函数返回当前会话的会话 ID,如果没有当前会话,则返回空字符串。如果失败,它将返回 false 。
PHP will generate a random session ID, if the $id parameter is not given. You may specify your own ID instead. The function returns the session id for the current session or the empty string if there is no current session. On failure, it returns false.
Example
请看以下示例:
Take a look at the following example −
<?php
// Starting the session
session_start();
$id = session_id();
echo "Session Id: ".$id ;
?>
浏览器会将一个随机字符串显示为 output −
The browser will show a random string as the output −
Session Id: mi3976f8ssethe9f04vq1ag6it
名为 PHPSESSID 的 cookie 会自动发送到用户的计算机,以存储唯一的会话标识符字符串。
A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
会话在服务器的临时目录中创建一个文件,其中存储已注册的会话变量及其值。此数据在该访问期间将对网站上的所有页面可用。
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
临时文件的位置由“php.ini”文件中的一个名为“session.save_path”的设置确定。
The location of the temporary file is determined by a setting in the "php.ini" file called "session.save_path".
Handling Session Variables
会话变量存储在关联数组 $_SESSION[] 中。在会话的生命周期内可以访问这些变量。
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
要创建新的会话变量,在 $_SESSION 数组中添加一个键值对 −
To create a new session variable, add a key-value pair in the $_SESSION array −
$_SESSION[ "var"]=value;
要回读会话变量的值,可以使用 echo/print 语句、或 var_dump() 或 print_r() 函数。
To read back the value of a session variable, you can use echo/print statements, or var_dump() or print_r() functions.
echo $_SESSION[ "var"];
要获取当前会话中所有会话变量的列表,可以使用 foreach 循环遍历 $_SESSION −
To obtain the list of all the session variables in the current session, you can use a foreach loop to traverse the $_SESSION −
foreach ($_SESSION as $key=>$val)
echo $key . "=>" . $val;
Example
以下示例启动一个会话,然后注册一个名为 counter 的变量,该变量在会话期间每次访问页面时都会递增。
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
使用 isset() function 检查会话变量是否已设置。
Use the isset() function to check if a session variable is already set or not.
以下 PHP 脚本在首次运行时启动会话,并设置一个名为 counter 的会话变量。当客户端再次访问同一 URL 时,由于会话变量已设置,因此计数器会增加。
The following PHP script starts a session when it runs for the first time, and sets a session variable named counter. When the client revisits the same URL again, since the session variable is already set, the counter is incremented.
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
} else {
$_SESSION['counter'] = 1;
}
$msg = "Number of visits in this session: ". $_SESSION['counter'];
?>
<?php
echo "$msg";
?>
多次刷新浏览器以模拟重复访问。浏览器显示计数器 −
Refresh the browser multiple times to simulate repeated visits. The browser displays the counter −
Number of visits in this session: 5
Destroying a PHP Session
PHP 会话可以被 session_destroy() 函数销毁。此函数不需要任何参数,并且一次调用可以销毁所有会话变量。如果您想销毁单个会话变量,则可以使用 unset() 函数取消设置会话变量。
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
以下是 unset a single variable 的示例 −
Here is an example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
以下是将会 destroy all the session variables 的调用 −
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
如果您可以在 php.ini 文件中将 session.auto_start 变量设置为 1,则当用户访问您的网站时,您不需要调用 start_session() 函数来启动会话。
You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
Example
以下 PHP 脚本呈现一个 HTML 表单。表单数据用于创建三个会话变量。超链接将浏览器带到另一个页面,该页面读回会话变量。
The following PHP script renders a HTML form. The form data is used to create three session variables. A hyperlink takes the browser to another page, which reads back the session variables.
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<h3>User's ID: <input type="text" name="ID"/></h3>
<h3>User's Name: <input type="text" name="name"/></h3>
<h3>User Type: <input type="text" name="type"/></h3>
<input type="submit" value="Submit" />
</form>
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_SESSION['ID'] = $_POST['ID'];
$_SESSION['Name'] = $_POST['name'];
$_SESSION['type'] = $_POST['type'];
echo "<h2>Following Session variables Created</h2>";
foreach ($_SESSION as $key=>$val) {
echo "<h3>" . $key . "=>" . $val . "</h3>";
}
echo "<a href='test.php'><b>Click Here</b></a>";
}
?>
</body>
</html>
将此代码作为“hello.php”保存在文档根目录文件夹中,并在客户端浏览器中打开它。
Save this code as "hello.php" in the document root folder, and open it in a client browser.
按 Submit 按钮。浏览器将显示已创建的会话变量 −
Press the Submit button. The browser will show the session variables created −
浏览器通过遵循所示的链接导航到另一个页面。它读回会话变量。
The browser navigates to another page by following the link shown. It reads back the session variables.