Home> php教程> PHP开发> body text

Detailed explanation of session usage in PHP Page 1/2

高洛峰
Release: 2016-12-24 09:25:37
Original
1133 people have browsed it

Since the Session is stored on the server side in the form of a text file, there is no fear of the client modifying the Session content. In fact, in the session file on the server side, PHP automatically modifies the permissions of the session file, retaining only system read and write permissions, and cannot be modified through ftp, so it is much safer. PHPChina Open Source Community Portal

For cookies, assuming we want to verify whether the user is logged in, we must save the user name and password (possibly an md5 encrypted string) in the cookie, and verify it every time the page is requested. If the username and password are stored in the database, a database query must be executed every time, causing unnecessary burden on the database. Because we can't do just one verification. Why? Because the information in the client cookie may be modified. If you store the $admin variable to indicate whether the user is logged in, when $admin is true, it means logged in, and when it is false, it means not logged in. After passing the verification for the first time, store $admin equal to true in the cookie, and there will be no need to verify next time. Okay, is this right? Wrong. If someone forges a $admin variable with a value of true, doesn’t that mean he or she will immediately gain administrative rights? It’s very unsafe.
 The Session is different. The Session is stored on the server side. Remote users cannot modify the contents of the session file. Therefore, we can simply store a $admin variable to determine whether to log in. After the first verification is passed, set the $admin value to true. Determine whether the value is true. If not, go to the login interface, which can reduce a lot of database operations. And it can reduce the insecurity of passing the password every time to verify the cookie (session verification only needs to be passed once, if you do not use the SSL security protocol). Even if the password is md5 encrypted, it can be easily intercepted.
Of course there are many advantages to using session, such as easy control and user-defined storage (stored in the database). I won’t say much more here.
 Does the session need to be set in php.ini? Generally not required, because not everyone has the permission to modify PHP.ini. The default storage path of the session is the system temporary folder of the server. We can customize it and store it in our own folder, which I will introduce later.
 Start by introducing how to create a session. Very simple, really.
 Start the session session and create a $admin variable:

  // 启动 session   session_start();   // 声明一个名为 admin 的变量,并赋空值。   $_session["admin"] = null;   ?>
Copy after login

 If you use Seesion, or the PHP file wants to call the Session variable, you must start it before calling the Session, using the session_start() function. You don’t need to set anything else, PHP automatically creates the session file.
 After executing this program, we can go to the system temporary folder to find the session file. Generally, the file name is in the form: sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it with an editor and take a look at its content:
 admin|N;
Generally, the content is structured like this:
Variable name|Type: length: value;
Separate each variable with a semicolon. Some can be omitted, such as length and type.
 Let’s take a look at the verification program. Assume that the database stores the username and md5 encrypted password:

  // 表单提交后…   $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,判断是否登陆:   // 防止全局变量造成安全隐患   $admin = false;   // 启动会话,这步必不可少   session_start();   // 判断是否登陆   if (isset($_SESSION["admin"]) && $_session["admin"] === true)   {   echo “您已经成功登陆”;   }   else   {   // 验证失败,将 $_session["admin"] 置为 false   $_session["admin"] = false;   die(“您无权访问”);   }   ?>
Copy after login

 Isn’t it very simple? Think of $_session as an array stored on the server side. Each variable we register They are all keys of an array, and there is no difference from using an array.
 What should I do if I want to log out of the system? Just destroy the session.

  session_start();   // 这种方法是将原来注册的某个变量销毁   unset($_session["admin"]);   // 这种方法是销毁整个 session 文件   session_destroy(); ?>
Copy after login

 Can Session set the life cycle like Cookie? With Session, will Cookie be abandoned completely? I would say that it is most convenient to use Session in combination with Cookie.
 How does the Session determine the client user? It is determined 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. 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 session.
Let’s manually set the lifetime of the session:

  session_start();   // 保存一天   $lifeTime = 24 * 3600;   setcookie(session_name(), session_id(), time() + $lifeTime, “/”);   ?>
Copy after login

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

  // 保存一天   $lifeTime = 24 * 3600;   session_set_cookie_params($lifeTime);   session_start();   $_session["admin"] = true;   ?>
Copy after login

  如果客户端使用 IE 6.0 , session_set_cookie_params(); 函数设置 Cookie 会有些问题,所以我们还是手动调用 setcookie 函数来创建 cookie。
  假设客户端禁用 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 页面间传递。

  // 保存一天   $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;   ?>
Copy after login

  对于虚拟主机来说,如果所有用户的 Session 都保存在系统临时文件夹里,将给维护造成困难,而且降低了安全性,我们可以手动设置 Session 文件的保存路径,session_save_path()就提供了这样一个功能。我们可以将 session 存放目录指向一个不能通过 Web 方式访问的文件夹,当然,该文件夹必须具备可读写属性。

  // 设置一个存放目录   $savePath = “./session_save_dir/”;   // 保存一天   $lifeTime = 24 * 3600;   session_save_path($savePath);   session_set_cookie_params($lifeTime);   session_start();   $_session["admin"] = true;   ?>
Copy after login

  同 session_set_cookie_params(); 函数一样,session_save_path() 函数也必须在 session_start() 函数调用之前调用。
  我们还可以将数组,对象存储在 session 中。操作数组和操作一般变量没有什么区别,而保存对象的话,PHP 会自动对对象进行序列化(也叫串行化),然后保存于 session 中。下面例子说明了这一点:

  class person   {   var $age;   function output() {   echo $this->age;   }   function setAge($age) {   $this->age = $age;   }   }   ?>
Copy after login

  setage.PHP

  session_start();   require_once “person.PHP”;   $person = new person();   $person->setAge(21);   $_session['person'] = $person;   echo “check here to output age”;   ?>
Copy after login

  output.PHP

  // 设置回调函数,确保重新构建对象。   ini_set(‘unserialize_callback_func', ‘mycallback');   function mycallback($classname) {   $classname . “.PHP”;   }   session_start();   $person = $_session["person"];   // 输出 21   $person->output();   ?>
Copy after login

  当我们执行 setage.php 文件的时候,调用了 setage() 方法,设置了年龄为 21,并将该状态序列化后保存在 session 中(PHP 将自动完成这一转换),当转到 output.php 后,要输出这个值,就必须反序列化刚才保存的对象,又因为在解序列化的时候需要实例化一个未定义类,所以我们定义了以后回调函数,自动包含 person.PHP 这个类文件,因此对象被重构,并取得当前 age 的值为 21,然后调用 output() 方法输出该值。

更多PHP中session使用方法详解第1/2页相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!