Analysis of the specific usage of PHP session_PHP tutorial

WBOY
Release: 2016-07-15 13:29:33
Original
766 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.

For cookies, assuming we want to verify whether the user is logged in, we must save the username 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. Yes, 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? Very unsafe.

The PHP session is different. 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, and set it after passing the first verification. The value of $admin is true. In the future, it will be determined 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 PHP session need to be set in php.ini? Generally not needed, because not everyone has the permission to modify php.ini. The default storage path of Session is the system temporary folder of the server. We can customize it and store it in our own folder. I will introduce this later. .

Start introducing how to create a Session. Very simple, really.

Start a Session and create a $admin variable:

<ol class="dp-xml">
<li class="alt"><span><span>// 启动 Session   </span></span></li>
<li class=""><span>session_start();   </span></li>
<li class="alt"><span>// 声明一个名为 admin 的变量,并赋空值。   </span></li>
<li class=""><span>$_SESSION["admin"] = null;   </span></li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span><span></span>
</li>
</ol>
Copy after login

If you use Seesion, or the PHP file wants to call the Session variable, you must start it before calling the PHP session, using the session_start() function. You don’t need to set anything else, PHP automatically completes the creation of the Session file.

After executing this program, we can go to the system temporary folder to find the Session file. The general 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 has this structure:

Variable name|Type: length: value ;

and separate each variable with a semicolon. Some can be omitted, such as length and type.

Let’s take a look at the verification procedure, assuming that the database stores the username and md5 encrypted password:

<ol class="dp-xml">
<li class="alt"><span><span>login.php  </span></span></li>
<li class=""><span> </span></li>
<li class="alt"><span>// 表单提交后...   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">posts</font></span><span> = $_POST;   </span>
</li>
<li class="alt"><span>// 清除一些空白符号   </span></li>
<li class="">
<span>foreach ($posts as $</span><span class="attribute"><font color="#ff0000">key</font></span><span> =</span><span class="tag"><strong><font color="#006699">></font></strong></span><span> $value)   </span>
</li>
<li class="alt"><span>{   </span></li>
<li class=""><span>$posts[$key] = trim($value);   </span></li>
<li class="alt"><span>}   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">password</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">md5</font></span><span>($posts["password"]);   </span>
</li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">username</font></span><span> = $posts["username"];  </span>
</li>
<li class=""><span> </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">query</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">"SELECT `username` FROM `user` WHERE `password` = '$password'"</font></span><span>;   </span>
</li>
<li class=""><span>// 取得查询结果   </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">userInfo</font></span><span> = $DB-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>getRow($query);  </span>
</li>
<li class=""><span> </span></li>
<li class="alt"><span>if (!empty($userInfo))   </span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span>if ($userInfo["username"] == $username)   </span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span>// 当验证通过后,启动PHP会话Session</span></li>
<li class=""><span>session_start();   </span></li>
<li class="alt"><span>// 注册登陆成功的 admin 变量,并赋值 true   </span></li>
<li class=""><span>$_SESSION["admin"] = true;   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span>else   </span></li>
<li class="alt"><span>{   </span></li>
<li class=""><span>die("用户名密码错误");   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span>}   </span></li>
<li class="alt"><span>else   </span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span>die("用户名密码错误");   </span></li>
<li class=""><span>}  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

We start the Session on the page that requires user verification to determine whether to log in:

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 PHP session.

<ol class="dp-xml">
<li class="alt"><span><span>// 防止全局变量造成安全隐患   </span></span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">admin</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">false</font></span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li class=""><span>// 启动会话,这步必不可少   </span></li>
<li class="alt"><span>session_start();  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>// 判断是否登陆   </span></li>
<li class=""><span>if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true)   </span></li>
<li class="alt"><span>{   </span></li>
<li class=""><span>echo "您已经成功登陆";   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span>else   </span></li>
<li class="alt"><span>{   </span></li>
<li class=""><span>// 验证失败,将 $_SESSION["admin"] 置为 false  </span></li>
<li class="alt"><span>$_SESSION["admin"] = false;   </span></li>
<li class=""><span>die("您无权访问");   </span></li>
<li class="alt"><span>}  </span></li>
<li class=""><span> </span></li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

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 PHP session.

Let’s manually set the Session lifetime:

<ol class="dp-xml">
<li class="alt"><span><span>session_start();   </span></span></li>
<li class=""><span>// 这种方法是将原来注册的某个变量销毁  </span></li>
<li class="alt"><span>unset($_SESSION["admin"]);  </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>// 这种方法是销毁整个 Session 文件  </span></li>
<li class=""><span>session_destroy();  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

In fact, Session also provides a function session_set_cookie_params(); to set the survival of Session Periodically, this function must be called before the session_start() function is called:

<ol class="dp-xml">
<li class="alt"><span><span>session_start();   </span></span></li>
<li class=""><span>// 保存一天   </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">lifeTime</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">24</font></span><span> * 3600;   </span>
</li>
<li class=""><span>setcookie(session_name(), session_id(), time() + $lifeTime, "/");  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

<ol class="dp-xml">
<li class="alt"><span><span>// 保存一天   </span></span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">lifeTime</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">24</font></span><span> * 3600;   </span>
</li>
<li class="alt"><span>session_set_cookie_params($lifeTime);   </span></li>
<li class=""><span>session_start();   </span></li>
<li class="alt"><span>$_SESSION["admin"] = true;  </span></li>
<li class=""><span> </span></li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

如果客户端使用 IE 6.0 , session_set_cookie_params(); 函数设置 Cookie 会有些问题,所以我们还是手动调用 setcookie 函数来创建 cookie。

假设客户端禁用 Cookie 怎么办?没办法,所有生存周期都是浏览器进程了,只要关闭浏览器,再次请求页面又得重新注册PHP会话Session。那么怎么传递 Session ID 呢?通过 URL 或者通过隐藏表单来传递,PHP 会自动将 Session ID 发送到 URL 上,URL 形如:http://www.openphp.cn/index.php? ... e5b44cfa01d49cf9669,其中 URL 中的参数 PHPSESSID 就是 Session ID了,我们可以使用 $_GET 来获取该值,从而实现 Session ID 页面间传递。

<ol class="dp-xml">
<li class="alt"><span><span>// 保存一天   </span></span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">lifeTime</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">24</font></span><span> * 3600;   </span>
</li>
<li class="alt"><span>// 取得当前 Session 名,默认为 PHPSESSID   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">sessionName</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">session_name</font></span><span>();   </span>
</li>
<li class="alt"><span>// 取得 Session ID   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">sessionID</font></span><span> = $_GET[$sessionName];   </span>
</li>
<li class="alt"><span>// 使用 session_id() 设置获得的 Session ID   </span></li>
<li class=""><span>session_id($sessionID);  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>session_set_cookie_params($lifeTime);   </span></li>
<li class="alt"><span>session_start();   </span></li>
<li class=""><span>$_SESSION["admin"] = true;  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

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

<ol class="dp-xml">
<li class="alt"><span><span>// 设置一个存放目录   </span></span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">savePath</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">"./session_save_dir/"</font></span><span>;   </span>
</li>
<li class="alt"><span>// 保存一天   </span></li>
<li class="">
<span>$</span><span class="attribute"><font color="#ff0000">lifeTime</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">24</font></span><span> * 3600;   </span>
</li>
<li class="alt"><span>session_save_path($savePath);   </span></li>
<li class=""><span>session_set_cookie_params($lifeTime);   </span></li>
<li class="alt"><span>session_start();   </span></li>
<li class=""><span>$_SESSION["admin"] = true;  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

同 session_set_cookie_params(); 函数一样,session_save_path() 函数也必须在 session_start() 函数调用之前调用。

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

<ol class="dp-xml">
<li class="alt"><span><span>person.php  </span></span></li>
<li class=""><span> </span></li>
<li class="alt"><span>class person   </span></li>
<li class=""><span>{   </span></li>
<li class="alt"><span>var $age;   </span></li>
<li class=""><span>function output() {   </span></li>
<li class="alt">
<span>echo $this-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>age;   </span>
</li>
<li class=""><span>}  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span>function setAge($age) {   </span></li>
<li class="alt">
<span>$this-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span class="attribute"><font color="#ff0000">age</font></span><span> = $age;   </span>
</li>
<li class=""><span>}   </span></li>
<li class="alt"><span>}   </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
<li class="alt"><span> </span></li>
<li class=""><span>setage.php  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>session_start();   </span></li>
<li class=""><span>require_once "person.php";   </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">person</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">new</font></span><span> person();   </span>
</li>
<li class="">
<span>$person-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>setAge(21);   </span>
</li>
<li class="alt"><span>$_SESSION['person'] = $person;   </span></li>
<li class=""><span>echo "check here to output age";  </span></li>
<li class="alt"><span> </span></li>
<li class="">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
<li class="alt"><span> </span></li>
<li class=""><span>output.php  </span></li>
<li class="alt"><span> </span></li>
<li class=""><span> </span></li>
<li class="alt"><span>// 设置回调函数,确保重新构建对象。   </span></li>
<li class=""><span>ini_set('unserialize_callback_func', 'mycallback');   </span></li>
<li class="alt"><span>function mycallback($classname) {   </span></li>
<li class=""><span>include_once $classname . ".php";   </span></li>
<li class="alt"><span>}   </span></li>
<li class=""><span>session_start();   </span></li>
<li class="alt">
<span>$</span><span class="attribute"><font color="#ff0000">person</font></span><span> = $_SESSION["person"];   </span>
</li>
<li class=""><span>// 输出 21   </span></li>
<li class="alt">
<span>$person-</span><span class="tag"><strong><font color="#006699">></font></strong></span><span>output();  </span>
</li>
<li class=""><span> </span></li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

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

另外,我们还可以使用 session_set_save_handler 函数来自定义PHP会话Session的调用方式。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446365.htmlTechArticle由于 Session 是以文本文件形式存储在服务器端的,所以不怕客户端修改 Session 内容。实际上在服务器端的 Session 文件,PHP 自动修改 Session...
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 Tutorials
More>
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!