search
HomeBackend DevelopmentPHP TutorialGetting started with PHP session (session time setting)_PHP tutorial

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

Jul 13, 2016 pm 05:30 PM
cookiephpsessionsessionusegetting Startedexistrightdeveloptimeyesset up

在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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)