Home >Backend Development >PHP Tutorial >PHP session usage experience summary_PHP tutorial

PHP session usage experience summary_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 10:33:11720browse

What is session

The Chinese translation of Session is called "conversation". Its original meaning refers to a series of actions/messages that have a beginning and an end. For example, when making a phone call, the series of processes from picking up the phone to dialing to hanging up the phone can be called a session. The current understanding of session in society is very confusing: sometimes we can see the words "During a browser session,...", the session here refers to the period from the opening of a browser window to the closing; you can also see When referring to the sentence "the user (client) during a session", it may refer to a series of actions of the user (usually a series of actions related to a specific purpose, such as from logging in to purchasing goods to checking out. Such an online shopping process; however, sometimes it may just refer to a connection; the difference can only be inferred from the context

.

However, when the word session is associated with a network protocol, it often implies two meanings: "connection-oriented" and/or "maintaining state". "Connection-oriented" refers to the communication between the two parties before communication. You must first establish a communication channel, such as making a phone call, and communication cannot begin until the other party answers the phone. "Maintaining status" means that the communicating party can associate a series of messages so that the messages can depend on each other. For example, a waiter can recognize an old customer who comes again and remember that the customer owed the store a dollar last time. . Examples of this category are "a TCP session" or "a POP3 session".

Given that this confusion is irreversible, it is difficult to have a unified standard for defining session. When reading session-related information, we can only rely on context to infer and understand. But we can understand it this way: For example, when we make a call, from the moment the call is made to the moment we hang up, the phone remains connected, so this connected state is called session. It is a public variable that always exists during the interaction between the visitor and the entire website. When the client does not support COOKIE, in order to ensure that the data is correct and safe, the SESSION variable is used. Visitors to the website are assigned a unique identifier, a so-called session ID. It is either stored in a client-side cookie or passed via the URL.

The invention of SESSION filled the limitations of the HTTP protocol: the HTTP protocol is considered a stateless protocol and cannot know the user's browsing status. When it completes the response on the server side, the server loses contact with the browser. This is consistent with the original purpose of the HTTP protocol. The client only needs to simply request the server to download certain files. Neither the client nor the server needs to record each other's past behavior. Each request is independent. It's like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

Therefore, the user's relevant information is recorded through SESSION (cookie is another solution) for confirmation when the user makes a request to the web server again as this identity. The invention of sessions allows a user to preserve his or her information when switching between multiple pages. Website programmers all have this experience. The variables in each page cannot be used in the next page (although form and url can also be implemented, but these are very unsatisfactory methods), while the variables registered in SESSION are Can be used as a global variable.

So what is the use of SESSION? Everyone has used a shopping cart when shopping online. You can add the products you choose to the shopping cart at any time, and finally go to the checkout counter to check out. During the entire process, the shopping cart has been playing the role of temporarily storing the selected products. It is used to track the user's activities on the website. This is the role of SESSION. It can be used for user identity authentication, program status recording, and between pages. Parameter passing, etc.

COOKIE technology is used in the implementation of SESSION. SESSION will save a COOKIE containing session_id (SESSION number) on the client side; save other session variables on the server side, such as session_name, etc. When the user requests the server, the session_id is also sent to the server. By extracting the variables saved on the server side through the session_id, you can identify who the user is. It is also not difficult to understand why SESSION sometimes fails.

When the client disables COOKIE (click "Tools" - "Internet Options" in IE, click "Security" - "Custom Level" item in the pop-up dialog box, and set "Allow each conversation COOKIE" (disabled), session_id will not be passed, and SESSION will be invalid. However, php5 can automatically check the cookie status on the linux/unix platform. If the client is disabled, the system will automatically append the session_id to the url and pass it. Windows hosts do not have this feature.

Session common functions and usage

Session_start(): Start a session or return an existing session.

Note: This function has no parameters and the return value is true. If you use cookie-based sessions, the browser must not produce any output before using Session_start(), otherwise the following error will occur:

Warning: Cannot send session cache limiter - headers already sent 
(output started at /usr/local/apache/htdocs/cga/member/1.php:2)…………  

You can enable session.auto_start=1 in php.ini, so that you don’t need to call session_start() every time before using the session. But there are some limitations to enabling this option, if session.auto_start is indeed enabled, you cannot put the object into the session because the class definition must be loaded before starting the session to recreate the object in the session.

All registered variables will be serialized after the request is completed. Variables that are registered but not defined are marked as undefined. These variables are also not defined by the session module on subsequent accesses unless the user later defines them.

Warning: Some types of data cannot be serialized and therefore cannot be saved in the session. Including resource variables or objects with circular references (that is, one object passes a reference to itself to another object).

Register SESSION variable:

PHP5 uses $_SESSION[‘xxx’]=xxx to register the SESSION global variable. The usage methods of GET, POST and COOKIE are similar.

Note: session_register(), session_unregister, and session_is_registered are no longer used under php5 unless register_globle is set to on in php.ini. However, for security reasons, it is strongly recommended to turn off register_globle. The use of HTTP_SESSION_VARS is no longer recommended, and the official recommendation is to use $_SESSION instead. For example:

Page1.php

<?php
Session_start();       //使用SESSION前必须调用该函数。
$_SESSION['name']="NowaMagic";   //注册一个SESSION变量
$_SESSION['passwd']="hellomagic";
$_SESSION['time']=time();
echo '<br />通过COOKIE传递SESSION';   //如果客户端支持cookie,可通过该链接传递session到下一页。
echo '<br />通过URL传递SESSION';//客户端不支持cookie时,使用该办法传递session.
?>  

Page2.php

<?php
session_start();
echo $_SESSION['name']; //
echo $_SESSION['passwd'];   //
echo date('Y m d H:i:s', $_SESSION['time']);
echo '<br />返回山一页';
?>  

There are two ways to pass a session ID:

One is a cookie and the other is a URL parameter.

The session module supports both methods. Cookies are more optimized, but since they are not always available, alternatives are also provided. The second method embeds the session ID directly into the middle of the URL. PHP can convert connections transparently. Unless you are using PHP 4.2 or newer, you need to manually activate it when compiling PHP. Under Unix, use the --enable-trans-sid configuration option. If this configuration option and the runtime option session.use_trans_sid are both activated (php.ini modified), the relative URI will automatically be modified to include the session ID.

  • session_id
  • session_id() is used to set or get the current session_id. In php5, you can either use session_id() or obtain the session_id and session_name of the current session through the SID attached to the url.

    If session_id() has a specific value, it will replace the current session_id value. The session must be started before using this function: session_start();

    When we use session cookies, if a session_id() value is specified, a cookie value will be sent to the client every time session_start() is started. Regardless of whether the current session_id is equal to the specified value.

    session_id() If no value is specified, the current session_id() is returned; if the current session is not started, an empty string is returned.

  • Check if session exists
  • In previous php versions, session_is_register() was usually used to check whether the session exists. If you use $_SESSION['XXX']=XXX to register session variables, the session_is_register() function no longer works. You can use isset($_SESSION['xxx']) instead.

  • Change session_id
  • session_regenerate_id() returns true if the change is successful and false if it fails. Using this function can change the session_id for the current session, but does not change other information of the current session. For example:

    <?php
    session_start();
    $old_sessionid = session_id();
    session_regenerate_id();
    $new_sessionid = session_id();
    echo "原始 SessionID: $old_sessionid<br />";
    echo "新的 SessionID: $new_sessionid<br />";
    echo"<pre class="brush:php;toolbar:false">";
    print_r($_SESSION);
    echo"
    "; ?>

  • session_name()
  • Return the name of the current session or change the name of the current session. If you want to change the name of the current session, this function must be called before session_start(). Note: session_name cannot only consist of numbers, it must contain at least one letter. Otherwise, a new session id will be generated every time. Example of session rename:

    <?php
    	$previous_name = session_name("WebsiteID");
    	echo "新的session名为: $previous_name";
    ?>    

  • How to delete session
  • unset ($_SESSION['xxx']) deletes a single session, unset($_SESSION['xxx']) is used to unregister a registered session variable. Its function is the same as session_unregister(). session_unregister() is no longer used in PHP5 and can be relegated to obsolescence. unset($_SESSION) This function must not be used, it will destroy the global variable $_SESSION, and there is no feasible way to restore it. Users can also no longer register the $_SESSION variable.

    $_SESSION=array() delete multiple sessions

    session_destroy() ends the current session and clears all resources in the session. This function will not unset (release) global variables related to the current session, nor will it delete the client's session cookie. PHP's default session is based on cookies. If you want to delete cookies, you must use the setcookie() function. Return value: Boolean value. Function description: This function ends the current session. This function has no parameters and the return value is true.

    session_unset() This function no longer works if $_SESSION is used. Since PHP5 must use $_SESSION, this function can be relegated to the sidelines.

    下面是 PHP 官方关于删除 session 的案例:

    <?php
    	// 初始化session.
    	session_start();
    	/*** 删除所有的session变量..也可用unset($_SESSION[xxx])逐个删除。****/
    	$_SESSION = array();
    	/***删除sessin id.由于session默认是基于cookie的,所以使用setcookie删除包含session id的cookie.***/
    	if (isset($_COOKIE[session_name()])) 
    	{
       		setcookie(session_name(), '', time()-42000, '/');
    	}
    	// 最后彻底销毁session.
    	session_destroy();
    ?>    

由此我们可以得出删除Session的步骤:

  1. session_start();
  2. $_SESSION=array()/unset($_SESSION['xxx'])
  3. session_destroy()

SESSION安全:

会话模块不能保证存放在会话中的信息只能被创建该会话的用户看到。根据其存放的数据,还需要采取更多措施来主动保护会话的完整性。

评估会话中携带的数据并实施附加保护措施通常要付出代价,降低用户的方便程度。例如,如果要保护用户免于受简单的社交策略侵害(注:指在 URL 中显示的会话 ID 会被别人在电脑屏幕上看到,或被别的网站通过 HTTP Referer 得到等),则应该启用 session.use_only_cookies。此情形下,客户端必须无条件启用 cookie,否则会话就不工作。

有几种途径会将现有的会话 ID 泄露给第三方。泄露出的会话 ID 使第三方能够访问所有与指定 ID 相关联的资源。第一,URL 携带会话 ID。如果连接到外部站点,包含有会话 ID 的 URL 可能会被存在外部站点的 Referer 日志中。第二,较主动的攻击者可能会侦听网段的数据包。如果未加密,会话 ID 会以明文方式在网络中流过。对此的解决方式是在服务器上实施 SSL 并强制用户使用。

默认情况下,所有与特定会话相关的数据都被存储在由 INI 选项 session.save_path 指定的目录下的一个文件中。对每个会话会建立一个文件(不论是否有数据与该会话相关)。这是由于每打开一个会话即建立一个文件,不论是否有数据写入到该文件中。注意由于和文件系统协同工作的限制,此行为有个副作用,有可能造成用户定制的会话处理器(例如用数据库)丢失了未存储数据的会话。

上面介绍函数下文将会用到,但还有一些有关session的函数也介绍一下:

session_encode
函数功能:sesssion信息编码
函数原型:string session_encode(void);
返回值:字符串
功能说明:返回的字符串中包含全局变量中各变量的名称与值,形式如:
a|s:12:"it is a test";c|s:4:"lala"; 
a是变量名 s:12代表变量a的值"it is a test的长度是12 变量间用分号”;”分隔。  
session_decode
函数功能:sesssion信息解码
函数原型:boolean session_decode (string data)
返回值:布尔值
功能说明:这个函数可将session信息解码,成功则返回逻辑值true  

PHP5 不再使用 session_id,而是把它变成一个常量 SID,并保存在 cookie 中。如果客户端禁用了 cookie,php 会自动通过 url 自动传动传递 SID,其条件是设置 php.ini 中的 session.use_trans_sid = 1。此时即使客户端即使禁用了 cookie 也没关系了。用 strip_tags() 来输出 SID 以避免 XSS 相关的攻击。

Session跨页传递问题:

session跨页传递需要考虑三种情况:

  1. 客户端禁用了cookie。
  2. 浏览器出现问题,暂时无法存取cookie
  3. php.ini 中的 session.use_trans_sid = 0 或者编译时没有打开 --enable-trans-sid 选项

为什么会这样呢?下面解释一下原因:

Session 文件分为两部分:session 变量保存在服务器端(默认以文件方式存储 session);而 session id 则以 cookie 形式保存在客户端。(注意:session 默认是基于 cookie 的)。

当用户的浏览器向服务器提出请求时,同时发送包含 session id 的 cookie(默认情况下)。服务器根据客户端提供的 session id 来得到用户的文件,即保存在服务器端的 session 变量值。事实上,session id 可以使用客户端的 Cookie 或者 Http1.1 协议的 Query_String(就是访问的URL的“?”后面的部分)来传送给服务器,然后服务器读取 Session 的目录。也就是说,session id 是取得存储在服务上的 session 变量的身份证。当代码 session_start(); 运行的时候,就在服务器上产生了一个 session 文件,随之也产生了与之唯一对应的一个 session id,定义 session 变量以一定形式存储在刚才产生的 session 文件中。通过 session id,可以取出定义的变量。跨页后,为了使用 session,你必须又执行 session_start();将又会产生一个 session 文件,与之对应产生相应的 session id,用这个 session id 是取不出前面提到的第一个 session 文件中的变量的,因为这个session id 不是打开它的“钥匙”。如果在 session_start(); 之前加代码 session_id($session id);将不产生新的 session 文件,直接读取与这个 id对应的 session 文件。

PHP 中的 session 在默认情况下是使用客户端的 Cookie 来保存 session id 的,所以当客户端的 cookie 出现问题的时候就会影响session 了。必须注意的是:session 不一定必须依赖 cookie,这也是 session 相比 cookie 的高明之处。当客户端的 Cookie 被禁用或出现问题时,PHP 会自动把 session id 附着在 URL 中,这样再通过 session id 就能跨页使用 session 变量了。但这种附着也是有一定条件的,其一:“php.ini中的session.use_trans_sid = 1 或者编译时打开打开了 --enable-trans-sid 选项”;其二:运行 PHP 的服务器必须是 unix/linux 系统,windows 不具备此项功能。

明白了以上的道理,我们就可以得出解决session跨页传递问题的三条途径:

  1. 设置 php.ini 中的 session.use_trans_sid = 1 或者编译时打开打开了 --enable-trans-sid 选项,让 PHP 自动跨页传递 session id。
  2. 手动通过 URL 传值、隐藏表单传递 session id。
  3. 用文件、数据库等形式保存 session_id,在跨页过程中手动调用。

下面举例说明:

第一种情况:

page1.php

<?php
session_start();
$_SESSION['var1']="中华人民共和国";
$url="<a href="."\"s2.php\">下一页</a>";
echo $url;
?>  

page2.php

<?php
session_start();
echo "传递的session变量var1的值为:".$_SESSION['var1'];
?>  

运行以上代码,在客户端cookie正常的情况下,应该可以在得到结果“中华人民共和国”。

现在你手动关闭客户端的cookie,再运行,可能得不到结果了吧。如果得不到结果,再“设置php.ini中的session.use_trans_sid = 1或者编译时打开打开了--enable-trans-sid选项”,又得到结果“中华人民共和国”。

第二种途径:

s1.php

<?php
	session_start();
	$_SESSION['var1']="中华人民共和国";
	$sn = session_id();
	//PHP5定义了一个常量SID来表示session_id(),$url还可以写成$url='<a href="page2.php?' . SID . '">下一页</a>';
	$url="<a href="."\"s2.php?s=".$sn."\">下一页</a>";    
	echo $url;
?>  

s2.php

<?php
session_id($_GET['s']);
session_start();
echo "传递的session变量var1的值为:".$_SESSION['var1'];
?>  

第三种途径:

login.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=??????">
</head>
<body>
请登录:
<form name="login" method="post" action="mylogin1.php">
用户名:<input type="text" name="name"><br>
口 令:<input type="password" name="pass"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
mylogin1.php
<?php
$name=$_POST['name'];
$pass=$_POST['pass'];
if(!$name || !$pass) {
    echo "用户名或密码为空,请<a href=\"login.html\">重新登录</a>";
    die();
}
if (!($name=="laogong" && $pass=="123")) {
    echo "用户名或密码不正确,请<a href=\"login.html\">重新登录</a>";
    die();
}
//注册用户
ob_start();
session_start();
$_SESSION['user']= $name;
$psid=session_id();
$fp=fopen("e:\\tmp\\phpsid.txt","w+");
fwrite($fp,$psid);
fclose($fp);
//身份验证成功,进行相关操作
echo "已登录<br>";
echo "<a href=\"mylogin2.php\">下一页</a>";
?>  

mylogin2.php

<?php
	$fp=fopen("e:\\tmp\\phpsid.txt","r");
	$sid=fread($fp,1024);
	fclose($fp);
	session_id($sid);
	session_start();
	if(isset($_SESSION['user']) && $_SESSION['user']="laogong" ) 
	{
     	echo "已登录!";
	}
	else 
	{
    	//成功登录进行相关操作
    	echo "未登录,无权访问";
    	echo "请<a href=\"login.html\">登录</a>后浏览";
    	die();
	}
?>  

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752527.htmlTechArticle什么是session 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