这是一个非常简单的概念,称为会话。
当您访问 facebook 时,它会读取通过连接发送给它的唯一信息,例如 IP 地址、浏览器和其他一些次要信息,当这些信息结合起来时,它会创建一个唯一标识符。
然后这个唯一标识符被存储在一个文件中,如下所示:
d131dd02c5e6eec4693d9a0698aff95c.session
因此,当您使用凭据登录时,应用程序会将信息添加到此文件中,例如上次活动等。
当您离开并返回时,Facebook 将读取随每个请求发送的信息,然后将所有信息加在一起并创建一个唯一的哈希值,如果此哈希值存在于其存储系统中,它将打开并读取内容,并确切地知道你是谁。
所有这些都与 cookie 相结合,唯一的哈希被发送回浏览器并存储在您的 cookie 文件夹中,这个 cookie 文件会在每次请求时发送回 facebook。
PHP 会在内部为您处理此问题,因此启动和运行它是非常基本的:http://php.net/manual/en/features.sessions.php
这里有一个例子可以帮助你更深入地理解这个概念。
<?php
/*
* The session_start generates that hash and send a cookie to the browser
* This has to be first as you can only send cookie information before any content
*/
session_start();
/*
* Anything storeg within $_SESSION is what's been read from the session file and
* We check to see if the information has already been set on the first time the user
* visited the site
*/
if(!isset($_SESSION['hits']))
{
$_SESSION['hits'] = 0;
}
/*
* Now we increment the value every time the page is laoded
*/
$_SESSION['hits']++;
/*
* now we display the amount's of hits the user has loaded the page.
*/
echo 'You have vistited this site <strong>' . $_SESSION['hits'] . '</strong> times.';
?>
如果您加载此页面然后按 F5,会话值会在每次请求时递增,因此您应该会看到如下内容:
- 您已访问此网站 1 次。
- 您已访问此网站 2 次。
- 您已访问此网站 3 次。
- 您已访问此网站 4 次。
- ...
会话文件对每个访问者都是唯一的,这意味着当在 PHP 中使用会话变量时,它只适用于该用户,因此每个人都可以获得自己的单独会话。
在您研究时,可以在 StackOverflow 中搜索某些标签,例如 PHP 和会话。
https://stackoverflow.com/questions/tagged/php+session
这是一个关于 cookie 和会话优势等的好问题。
Purpose Of PHP Sessions and Cookies and Their Differences