php中session的使用
转自:http://www.openphp.cn/blog.php?blog_id=10
对比起 Cookie,Session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制,本文简单介绍 Session 的使用。
由于 Session 是以文本文件形式存储在服务器端的,所以不怕客户端修改 Session 内容。实际上在服务器端的 Session 文件,PHP 自动修改 Session 文件的权限,只保留了系统读和写权限,而且不能通过 ftp 修改,所以安全得多。
对于 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; ?>
执行完这个程序后,我们可以到系统临时文件夹找到这个 Session 文件,一般文件名形如:sess_4c83638b3b0dbf65583181c2f89168ec,后面是 32 位编码后的随机字符串。用编辑器打开它,看一下它的内容:
admin|N; 一般该内容是这样的结构:
变量名|类型:长度:值; 并用分号隔开每个变量。有些是可以省略的,比如长度和类型。
我们来看一下验证程序,假设数据库存储的是用户名和 md5 加密后的密码:
login.php
<?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' AND `username` = '$username'"; // 取得查询结果 $userInfo = $DB->getRow($query); if (!empty($userInfo)) { // 当验证通过后,启动 Session session_start(); // 注册登陆成功的 admin 变量,并赋值 true $_SESSION["admin"] = true; } else { die("用户名密码错误"); } ?>
<?php // 防止全局变量造成安全隐患 $admin = false; // 启动会话,这步必不可少 session_start(); // 判断是否登陆 if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true) { echo "您已经成功登陆"; } else { // 验证失败,将 $_SESSION["admin"] 置为 false $_SESSION["admin"] = false; die("您无权访问"); } ?>
如果要登出系统怎么办?销毁 Session 即可。
<?php session_start(); // 这种方法是将原来注册的某个变量销毁unset($_SESSION['admin']); // 这种方法是销毁整个 Session 文件session_destroy(); ?>
Session 是如何来判断客户端用户的呢?它是通过 Session ID 来判断的,什么是 Session ID,就是那个 Session 文件的文件名,Session ID 是随机生成的,因此能保证唯一性和随机性,确保 Session 的安全。一般如果没有设置 Session 的生存周期,则 Session ID 存储在内存中,关闭浏览器后该 ID 自动注销,重新请求该页面后,重新注册一个 Session ID。
如果客户端没有禁用 Cookie,则 Cookie 在启动 Session 会话的时候扮演的是存储 Session ID 和 Session 生存期的角色。
我们来手动设置 Session 的生存期:
<?php session_start(); // 保存一天 $lifeTime = 24 * 3600; setcookie(session_name(), session_id(), time() + $lifeTime, "/"); ?>
<?php // 保存一天 $lifeTime = 24 * 3600; session_set_cookie_params($lifeTime); session_start(); $_SESSION["admin"] = true; ?>
假设客户端禁用 Cookie 怎么办?没办法,所有生存周期都是浏览器进程了,只要关闭浏览器,再次请求页面又得重新注册 Session。那么怎么传递 Session ID 呢?通过 URL 或者通过隐藏表单来传递,PHP 会自动将 Session ID 发送到 URL 上,URL 形如:http://www.openphp.cn /index.php?PHPSESSID=bba5b2a240a77e5b44cfa01d49cf9669,其中 URL 中的参数 PHPSESSID 就是 Session ID了,我们可以使用 $_GET 来获取该值,从而实现 Session ID 页面间传递。
<?php // 保存一天 $lifeTime = 24 * 3600; // 取得当前 Session 名,默认为 PHPSESSID $sessionName = session_name(); // 取得 Session ID $sessionID = $_GET[$sessionName]; // 使用 session_id() 设置获得的 Session ID session_id($sessionID); session_set_cookie_params($lifeTime); session_start(); $_SESSION['admin'] = true; ?>
<?php // 设置一个存放目录 $savePath = './session_save_dir/'; // 保存一天 $lifeTime = 24 * 3600; session_save_path($savePath); session_set_cookie_params($lifeTime); session_start(); $_SESSION['admin'] = true; ?>
我们还可以将数组,对象存储在 Session 中。操作数组和操作一般变量没有什么区别,而保存对象的话,PHP 会自动对对象进行序列化(也叫串行化),然后保存于 Session 中。下面例子说明了这一点:
person.php
<?php class person { var $age; function output() { echo $this->age; } function setAge($age) { $this->age = $age; } } ?>
<?php session_start(); require_once 'person.php'; $person = new person(); $person->setAge(21); $_SESSION['person'] = $person; echo '<a href='output.php'>check here to output age</a>'; ?>
<?php// 设置回调函数,确保重新构建对象。 ini_set('unserialize_callback_func', 'mycallback'); function mycallback($classname) { include_once $classname . '.php'; } session_start(); $person = $_SESSION['person']; // 输出 21 $person->output(); ?>
另外,我们还可以使用 session_set_save_handler 函数来自定义 Session 的调用方式。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
