Home  >  Article  >  Backend Development  >  Getting started with PHP session (session time setting)_PHP tutorial

Getting started with PHP session (session time setting)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:30:10752browse

在PHP开发中对比起Cookie,Session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制,本文简单介绍 Session 的使用。

  由于 Session 是以文本文件形式存储在服务器端的,所以不怕客户端修改 Session 内容。实际上在服务器端的 Session 文件,PHP 自动修改 Session 文件的权限,只保留了系统读和写权限,而且不能通过 ftp 修改,所以安全得多。PHPChina 开源社区门户k%W%e2CY

   对于 Cookie 来说,假设我们要验证用户是否登陆,就必须在 Cookie 中保存用户名和密码(可能是 md5 加密后字符串),并在每次请求页面的时候进行验证。如果用户名和密码存储在数据库,每次都要执行一次数据库查询,给数据库造成多余的负担。因为我们并不能 只做一次验证。为什么呢?因为客户端 Cookie 中的信息是有可能被修改的。假如你存储 $admin 变量来表示用户是否登陆,$admin 为 true 的时候表示登陆,为 false 的时候表示未登录,在第一次通过验证后将 $admin 等于 true 存储在 Cookie,下次就不用验证了,这样对么?错了,假如有人伪造一个值为 true 的 $admin 变量那不是就立即取的了管理权限么?非常的不安全。

   而 Session 就不同了,Session 是存储在服务器端的,远程用户没办法修改 Session 文件的内容,因此我们可以单纯存储一个 $admin 变量来判断是否登陆,首次验证通过后设置 $admin 值为 true,以后判断该值是否为 true,假如不是,转入登陆界面,这样就可以减少很多数据库操作了。而且可以减少每次为了验证 Cookie 而传递密码的不安全性了(Session 验证只需要传递一次,假如你没有使用 SSL 安全协议的话)。即使密码进行了 md5 加密,也是很容易被截获的。

  当然使用 Session 还有很多优点,比如控制容易,可以按照用户自定义存储等(存储于数据库)。我这里就不多说了。

  Session 在 php.ini 是否需要设置呢?一般不需要的,因为并不是每个人都有修改 php.ini 的权限,默认 Session 的存放路径是服务器的系统临时文件夹,我们可以自定义存放在自己的文件夹里,这个稍后我会介绍。

  开始介绍如何创建 Session。非常简单,真的。

  启动 Session 会话,并创建一个 $admin 变量:

<?php
// 启动 Session
session_start();
// 声明一个名为 admin 的变量,并赋空值。
$_SESSION["admin"] = null;
?>

  如果你使用了 Seesion,或者该 PHP 文件要调用 Session 变量,那么就必须在调用 Session 之前启动它,使用 session_start() 函数。其它都不需要你设置了,PHP 自动完成 Session 文件的创建。

  执行完这个程序后,我们可以到系统临时文件夹找到这个 Session 文件,一般文件名形如:sess_4c83638b3b0dbf65583181c2f89168ec,后面是 32 位编码后的随机字符串。用编辑器打开它,看一下它的内容:

  admin|N;

  一般该内容是这样的结构:

  变量名|类型:长度:值;

  并用分号隔开每个变量。有些是可以省略的,比如长度和类型。

  我们来看一下验证程序,假设数据库存储的是用户名和 md5 加密后的密码:

<?php
// 表单提交后...
$posts = $_POST;
// 清除一些空白符号
foreach ($posts as $key => $value)
{
$posts[$key] = trim($value);
}
$password = md5($posts["password"]);
$username = $posts["username"];
$query = "SELECT `username` FROM `user` WHERE `password` = $password";
// 取得查询结果
$userInfo = $DB->getRow($query);
if (!empty($userInfo))
{
if ($userInfo["username"] == $username)
{
// 当验证通过后,启动 Session
session_start();
// 注册登陆成功的 admin 变量,并赋值 true
$_SESSION["admin"] = true;
}
else
{
die("用户名密码错误");
}
}
else
{
die("用户名密码错误");

  我们在需要用户验证的页面启动 Session,判断是否登陆:

<?php
// 防止全局变量造成安全隐患
$admin = false;
// 启动会话,这步必不可少
session_start();
// 判断是否登陆
if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true)
{
echo "您已经成功登陆";
}
else
{
// 验证失败,将 $_SESSION["admin"] 置为 false
$_SESSION["admin"] = false;
die("您无权访问");
}
?>

Isn’t it very simple? Just think of $_SESSION as an array stored on the server side. Each variable we register is the key of the array, which is no different from using an array.

What should I do if I want to log out of the system? Just destroy the Session.

<?php
session_start();
// This method is to destroy a previously registered variable
unset($_SESSION["admin"]);
// This The first method is to destroy the entire Session file
session_destroy();

Can Session set the life cycle like Cookie? Does having Session completely abandon Cookie? I would say that using Session in combination with Cookie is the most convenient.

How does Session determine the client user? It is judged by the Session ID. What is the Session ID is the file name of the Session file. The Session ID is randomly generated, so it can ensure uniqueness and randomness and ensure the security of the Session. Generally, if the Session life cycle is not set, the Session ID is stored in the memory. After closing the browser, the ID is automatically logged out. After re-requesting the page, a new Session ID is registered.

If the client does not disable cookies, the cookie plays the role of storing the Session ID and Session lifetime when starting the Session.

Let’s manually set the lifetime of the Session:

<?php
session_start();
// Save for one day
$lifeTime = 24 * 3600;
setcookie(session_name(), session_id(), time() + $lifeTime, "/");
?>

In fact, Session also provides a function session_set_cookie_params(); to set the lifetime of Session. This function must be called before the session_start() function is called:

<?php
// Save for one day
$lifeTime = 24 * 3600;
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>

If the client uses IE 6.0, the session_set_cookie_params(); function will have some problems setting cookies, so we still call the setcookie function manually to create cookies.

What if the client disables cookies? There is no way, the entire life cycle is the browser process. As long as you close the browser and request the page again, you have to re-register the Session. So how do you pass the Session ID? Passed through the URL or through a hidden form, PHP will automatically send the Session ID to the URL. The URL is in the form: http://www.openphp.cn/index.php?PHPSESSID=bba5b2a240a77e5b44cfa01d49cf9669, where the parameter PHPSESSID in the URL is the Session. ID, we can use $_GET to obtain the value, thereby transferring the Session ID between pages.

<?php
// Save for one day
$lifeTime = 24 * 3600;
// Get the current Session name, the default is PHPSESSID
$sessionName = session_name();
/ / Get Session ID
$sessionID = $_GET[$sessionName];
// Use session_id() to set the obtained Session ID
session_id($sessionID);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>

For virtual hosts, if all users’ Sessions are saved in the system temporary folder, it will cause difficulty in maintenance and reduce security. We can manually set the saving path of the Session file, session_save_path() provides has such a function. We can point the Session storage directory to a folder that cannot be accessed through the Web. Of course, the folder must have read-write attributes.

<?php
//Set a storage directory
$savePath = "./session_save_dir/";
// Save for one day
$lifeTime = 24 * 3600;
session_save_path( $savePath);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>

Like the session_set_cookie_params(); function, the session_save_path() function must also be called before the session_start() function is called.

We can also store arrays and objects in Session. There is no difference between operating an array and operating a general variable. When saving an object, PHP will automatically serialize the object (also called serialization) and then save it in the Session. The following example illustrates this:

<?php
class person
{
var $age;
function output() {
echo $this->age;
}
function setAge( $age) {
$this->age = $age;
}
}
?>
setage.php
<?php
session_start();
require_once "person.php";
$person = new person();
$person->setAge(21);
$_SESSION[person] = $person;
echo "<a href=output>check here to output age</a>";
?>
output.php
<?
// Set the callback function to ensure that the object is rebuilt.
ini_set(unserialize_callback_func, mycallback);
function mycallback($classname) {
$classname . ".php";
}
session_start();
$person = $_SESSION ["person"];
// Output 21
$person->output();
?>

When we

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/509215.htmlTechArticleCompared with Cookie in PHP development, Session is a session stored on the server side, which is relatively safe and unlike Cookie. There is a storage length limit. This article briefly introduces the use of Session. ...
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