This article will share with you a solution to PHP5 notes (COOKIE and SESSION) (share). The application has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#1. The HTTP protocol itself is stateless.
We all rely on the HTTP protocol to transmit information when surfing the Internet. For example, if we type the URL www.bokee.com into the browser and press Enter, you will find that the URL will become: http://www.bokee.com. The reason is that the web page you are browsing is based on the http protocol. The http protocol cannot record which websites the user often visits, what hobbies he or she has, nor can it record the user's ID account and password. This is the so-called statelessness of the HTTP protocol. The HTTP protocol itself is stateless, which 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 actions every time. The requests are all independent, just like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket. If you recognize them, they will definitely not recognize you.
2. How to understand cookie and session?
Since cookies and sessions are closely related, we introduce them together here.
For example: When I was in Henan, I often went to a deli to buy gluttonous ducks. In order to promote sales, the owner of the store issued a special promotion of "every 10 ducks purchased will be given away for free". Except for weddings and funerals at home, no one would buy 10 roast ducks at one time, right? So the boss has to think of a way to record the customer's consumption. There are three options here:
Ⅰ. The boss remembers the consumption quantity of each customer, and automatically gives one to the customer when he or she consumes 10 pieces. This is like the HTTP protocol itself is stateful and can remember the customer's activities behavior. But unfortunately, due to various considerations, the http protocol itself cannot be stateful, and the boss himself does not have such extraordinary memory, so this solution does not work!
Ⅱ. The boss issues a points card to the customer, which records the amount of consumption and usually has an expiration date. Every time when buying roast duck, if the customer shows this card, the boss will know that the customer has visited the store before. This approach is to maintain state on the client side, such as cookie technology. Open (Windows system) C:\Documents and Settings\Username\Cookies, you will find some small files in *.txt format, which are the "point cards" (cookies) sent to you by some websites when you browse them.
Ⅲ. The boss issues a membership card to the customer and records no information except the card number. Every time when buying roast duck, if the customer shows the card, the boss will move out of the store’s roster, find your card number and Add 1 point. This approach is to maintain state on the server side.
It's like session technology.
The biggest difference between cookie and session is: cookie is a reward card sent to the customer, which records all the customer's consumption information. Session issues a points card with only the card number (session ID) to the customer, and records all the customer's consumption information. Cookies are saved on the client side; sessions are saved on the server side, and session ids are saved on the client side. They are usually also a small cookie file. Since this small file has nothing except the session id (such as a card number), it is better than a cookie. Much safer.
3. What are cookies and sessions used for?
Common usage, such as downloading things from some websites requires members to log in first. The http protocol itself is stateless and there is no way to know whether the customer has logged in. What should I do? You can know it through cookies and sessions. Another example is online shopping. How does the shopping cart know which products the customer has selected? Cookies and sessions can also be recorded. All in all, cookies and sessions are technologies that can record customer status. Although they are different technologies, as long as cookies can do it, sessions can do it too!
COOKIE
1. What is a cookie?
0Cookie technology is a very controversial technology. Since its birth, it has become a focus of debate for the majority of network users and Web developers. Some Internet users, including some senior Web experts, are dissatisfied with its creation and promotion. This is not because the functionality of Cookie technology is too weak or for other technical performance reasons, but simply because they feel that the use of Cookies , causing harm to the privacy of network users. Because a cookie is a small text file saved on the user's browser by the Web server, it contains information about the user (such as an identification number, password, the way the user purchases on the Web site, or the number of times the user visits the site).
So what exactly is Cookie technology? Does it really bring harm to the personal privacy of Internet users? Let us read the following content before answering.
In the history of WEB technology development, the emergence of Cookie technology is a major change. First, Netscape introduced Cookie technology in its Netscape Navigator browser. Since then, the World Wide Web Association has begun to support the Cookie standard. Later, it was vigorously promoted by Microsoft (because the ASP technology used by Microsoft's IIS Web server uses Cookie technology to a large extent), that is, in Microsoft's Internet Explorer browser fully supports Cookie technology. Up to now, the vast majority of browsers support Cookie technology, or are at least compatible with the use of Cookie technology.
According to the definition in Netscape's official documentation, Cookie is a way for the server or script to maintain information on the client's workstation under the HTTP protocol. Cookies are small files saved on the user's browser by the Web server, which can contain information about the user (such as identification number, password, how the user purchases on the Web site or the number of times the user visits the site). Whenever a user connects to the server, the Web site can access the cookie information.
If you are using a windows system, please open C:\Documents and Settings\Username\Cookies, and you will find that there are many small files in *.txt format in this directory. That is the cookie file. Of course, you may not find anything in this directory because you have newly installed the system or have never browsed the Internet, or your browser has disabled cookies. Otherwise there will always be something in this directory.
In layman’s terms, browsers use one or more limited files to support cookies. These files are called cookie files on machines using Windows operating systems and magic cookie files on Macintosh machines. These files are used by websites to store cookie data on them. Websites can insert information into these cookie files, which may have side effects on some Internet users. Some users believe that this causes an invasion of personal privacy. What's worse, some people believe that cookies are an invasion of personal space and can cause security hazards to users' computers.
Currently some cookies are temporary and others are persistent. Temporary cookies are only saved on the browser for a specified period of time. Once the specified period of time expires, the cookie will be cleared by the system. For example, in PHP, Cookie is used to track the user's progress until the user leaves the website. A persistent cookie is saved in the user's cookie file and can still be called the next time the user returns.
Save Cookies in Cookie files. Some users will overly think that this will cause big problems. The main reason is that some users are worried that cookies will track users' online surfing habits, such as which types of sites users like to visit and what activities they like to engage in. I am afraid that once this kind of personal information falls into the hands of some people with ulterior motives, the individual may become the object of a lot of advertising garbage, or even suffer accidental damage. However, this worry will not occur at all, because users outside the website cannot obtain cookie information across the website. So it is impossible to use cookies for this purpose. However, due to some users' misunderstandings and "false rumors", some browser developers have no choice but to respond appropriately (for example, Netscape Navigator 4.0 and Internet Explorer 3.0 both provide the option to block cookies). Personally, I think there is no smoke without fire. If website programmers do not have rigorous thinking, cookies do have some security issues. However, these flaws are not enough to cover up the excellent qualities of cookies. Most people are still very happy to use them.
The result of waiting for Cookie technology for so long has forced many browser developers to provide flexible control over Cookies in their browsers. For example, the two current mainstream browsers Netscape Navigator and Internet Explorer handle cookies in this way: Netscape Navigator 4.0 can not only accept cookies for warning, but also block cookies; Internet Explorer 3.0 can also block cookies, but in Internet Explorer 4 In .0, you can only accept warnings without providing blocking options. However, in updated versions after Internet Explorer 4.0, the option to block cookies has been added.
In addition, many of the latest technologies can even block cookies on browsers that cannot block cookies. For example, you can limit the use of cookies by setting cookie files to different types. However, unfortunately, if you want to completely block cookies, you will definitely reject many site pages. Because today many Web site developers have fallen in love with the powerful functions of Cookie technology. For example, the use of Session objects cannot be separated from the support of Cookies.
2. How does Cookie work?
When a customer visits a website based on PHP technology, you can use the setcookie function in PHP to generate a cookie. After processing, the system sends the cookie to the client and saves it in C:\Documents and Settings\User name\Cookies directory. Cookies are part of the HTTP headers, so the setcookie function must be called before anything is sent to the browser. This restriction is the same as the header() function (if you need to understand the head() function, please check it yourself). When the customer visits the website again, the browser will automatically send the cookie corresponding to the site in the C:\Documents and Settings\Username\Cookies directory to the server, and the server will automatically convert the cookie sent from the client. into a PHP variable. In PHP5, cookies sent by the client will be converted into global variables. You can read it through $_COOKIE[‘xxx’].
Although there are still some Internet users today who are still arguing about Cookies, the vast majority of Internet users still tend to accept Cookies. Therefore, we can safely use Cookie technology to develop our WEB pages.
3. Cookie common functions
● SetCookie The function creates a Cookie and appends it to the end of the HTTP header. One thing that must be noted is that Cookie is part of the HTTP protocol header and is used to transfer information between the browser and the server, so it must be called before any content belonging to the HTML file itself is output. SetCookie function, even if there are spaces or blank lines before calling this function, it will not work. If setCookie() recognizes the second element, no element dares to recognize the first element. The prerequisite for using the setcookie() function is that the client's browser supports cookies. If the client disables it, setcookie() will be useless.
int SetCookie(string name, string value, int expire, string path, string domain, int secure, bool httponly);
Parameter description:
name; Set the name of the cookie variable.
value;Set the cookie value.
expire;Set cookie expiration time. If you want to save the cookie as a browser process, it will become invalid after the browser is closed. Then you can directly set expiretime to 0. Eg:setcookie("name","value",0). If this parameter is not set, closing the browser can also end a cookie.
Path: represents the directory on the web server, which defaults to the directory where the called page is located. There is one more thing to note here. For example, your site has several different directories (such as a shopping directory, a ForumDirectory), then if you only use Cookies without paths, Cookies set on pages in one directory cannot be seen on pages in another directory. In other words, Cookies is path-oriented. In fact, even if the path is not specified, the WEB server will automatically pass the current path to the browser, and specifying the path will force the server to use the set path. The way to solve this problem is to add the path and domain name when calling SetCookie. The format of the domain name can be "http://www.phpuser.com/" or ".phpuser.com". The part representing value in the SetCookie function will be automatically encoded when passed. In other words, if the value of value is "test value", it will become "test" when passed. value", the same method as URL. Of course, this is transparent to the program because PHP automatically decodes the cookie value when it receives it.
Domain: The domain name that the cookie can use, the default is the domain name of the called page. The domain name must contain two ".", so if you specify your top-level domain name, you must use ".mydomain.com". After setting a domain name, the domain name must be used to access the website for the cookie to be valid. If you use multiple domain names to access this page, then this field can be empty or the domain names accessing this cookie are all under the same domain.
secure: If set to "1", it means that the cookie can only be remembered by servers that the user's browser considers to be secure.
All parameters except name are optional. The three parameters value, path, and domain can be replaced with the empty string "", indicating that there is no setting; the expire and secure parameters are numerical and can be represented by 0. The expire parameter is a standard Unix time stamp, which can be obtained using the time() or mktime() function, in seconds. The secure parameter indicates whether this cookie is transmitted over the network through the encrypted HTTPS protocol.
httponly: If set to 1, it means that the cookie can only be used by the http protocol. Any scripting language, such as javascrīpt, cannot obtain the cookie created by PHP, which effectively weakens the attack from XSS. (Note: This is an option only available in PHP5, and I have never used it. I read the official manual and tried to translate . If you have any questions, please refer to the official manual.)
The currently set cookie does not take effect immediately, but can only be seen after the next page or refresh. This is because the cookie is passed to the client browser by the server in the set page, and will be viewed on the next page or after refresh. The reason why the server can take out the cookie from the client's machine and send it back to the server.
Grapevine
16-year-old German student cracked Hotmail through cookies
Adriaan Graas, a 16-year-old German student, is very interested in network security and web development. He also discovered a way to crack Hotmail. Today, more than a week later, Microsoft has yet to fix the vulnerability.
The idea of this little hacker is very simple. When a user logs in to Hotmail, the system will generate a cookie to facilitate the next login. Since the cookie is not bound to an IP, hackers can fake these cookies and use them to log in, without even knowing the victim's password or even email address. Through XSS hackers can insert a piece of javascrīpt code and use log scrīpt to send cookies to a web server. The script can be written in PHP, ASP, CGI and other languages.
Cookie application case:
●Create a cookie:
SetCookie()
●Create a cookie array:
One:
SetCookie(" CookieArray[]", "Value 1");
SetCookie("CookieArray[]", "Value 2");
Second:
SetCookie("CookieArray[0]", "Value 1" );
SetCookie("CookieArray[1]", "Value 2");
● Receiving and processing Cookies
PHP has very good support for receiving and processing Cookies and is completely automatic. , the same principle as GET and POST variables, very simple.
For example, if you set a cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a global variable that can be used directly, named $_COOKIE['MyCookie']. This variable The value is the value of Cookie. The same applies to arrays.
Examples are as follows: (assuming these have been set in previous pages and are still valid)
echo $_COOKIE['MyCookie'];
Example of taking out cookie array:
// 创建一个cookie数组 setcookie("cookie[three]", "cookiethree"); setcookie("cookie[two]", "cookietwo"); setcookie("cookie[one]", "cookieone"); // 页面刷新之后,用foreach提取cookie数组。 if (isset($_COOKIE['cookie'])) { foreach ($_COOKIE['cookie'] as $name => $value) { echo "$name : $value <br />\n"; } }
It’s that simple.
●Delete Cookie
To delete an existing Cookie, there are two ways:
1. Call SetCookie with only the name parameter, then the Cookie named this name will Deleted from the related computer;
setcookie("MyCookie"); //Delete MyCookie.
2. Set the cookie expiration time to time() or time()-1//It doesn’t matter how much time() is reduced, as long as it is the expiration time//, then this cookie will expire after browsing this page It has been deleted (in fact, it has become invalid). For example:
setcookie("MyCookie","Value",time()-1); //Delete MyCookie.
It should be noted that when a Cookie is deleted, its value is still valid on the current page.
If you want to save the cookie as a browser process, it will become invalid after the browser is closed. Then you can directly set expiretime to 0. For example: setcookie("name","value",0). If this parameter is not set, closing the browser can also end a cookie.
Cookie Notes
1. There cannot be any html output before SetCookie(). It recognizes the second one. No element dares to recognize the first one, even spaces and blank lines. no.
2. After SetCookie(), there will be no output when you call echo $_COOKIE["name"] on the current page. You must refresh or go to the next page to see the cookie value. the reason is simple. After SetCookie() is executed, a cookie is sent to the client. If you don't refresh or browse the next page, how can the client send the cookie back to you? After the browser creates a cookie, every request to the website will carry the cookie in the header; however, the cookie will never be sent to requests from other websites. And the browser will keep sending it until the cookie expires.
3. Restrictions on the use of cookies. The maximum number of cookies that can be created by a browser is 30, and each cookie cannot exceed 4KB. The total number of cookies that can be set by each WEB site cannot exceed 20. (This is what I read in the book. It should be that a web site cannot create more than 30 cookies. Otherwise, there are hundreds of cookies in my machine. Please give me some advice!)
4 , Cookies are stored on the client side. If the user disables cookies, your cookies will naturally have no effect! Today's browsers, whenever we send a cookie to the client, it intercepts it like a watchdog and asks the user whether to allow the cookie to enter. God, users are not experts. How many people know what cookies are? Maybe it will be treated as a virus and shut out.
SESSION
1. 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 It is a session. The current understanding of sessions 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 to closing of a browser window; 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 only refer to a connection; the difference can only be inferred from the context.
However, when the word session is used with networkWhen the protocol is associated, it often implies the two meanings of "connection-oriented" and/or "maintaining state". "Connection-oriented" means that the communicating parties must establish a communication channel before communicating. For example, when making a phone call, communication cannot begin until the other party answers the phone. "Keeping the 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 friend who comes again. The customer also remembers that the customer owed the store a dollar last time. Examples of this category are "a TCP session" or "a POP3 session".
In view of the fact that this confusion is irreversible, it is necessary to define a session. It is difficult to have a unified standard. When reading session-related information, we can only rely on context to infer understanding. But we can understand it this way: For example, when we make a phone call, from the moment we make the call to the time we hang up, because 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 secure, the SESSION variable is used. Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either stored in the client's cookie or passed through the URL.
The invention of SESSION Fills the limitations of the HTTP protocol: The HTTP protocol is considered a stateless protocol and cannot know the user's browsing status. After it completes the response on the server side, the server loses contact with the browser. This is consistent with the original nature of the HTTP protocol. The purpose is consistent. 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, just like a customer and an automatic server. The relationship between a vending machine or an ordinary (non-membership) hypermarket is the same.
Therefore, the relevant information of the user is recorded through SESSION (cookie is another solution), so that the user can log in to the web server in this capacity again. Confirm when a request is made. The invention of sessions allows a user to save his 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 the 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, parameter transfer between pages, etc.
The implementation of SESSION uses COOKIE technology. SESSION will save a COOKIE containing session_id (SESSION number) on the client side; other session variables, such as session_name, etc., will be saved on the server side. 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. At the same time, it is not difficult to understand why SESSION sometimes fails.
当客户端禁用COOKIE时(点击IE中的“工具”—“Internet选项”,在弹出的对话框里点击“安全”—“自定义级别”项,将“允许每个对话COOKIE”设为禁用),session_id将无法传递,此时SESSION失效。不过php5在linux/unix平台可以自动检查cookie状态,如果客户端设置了禁用,则系统自动把session_id附加到url上传递。windows主机则无此功能。
2、Session常见函数及用法?
●Session_start():开始一个会话或者返回已经存在的会话。
说明:这个函数没有参数,且返回值均为true。如果你使用基于cookie的session(cookie-based sessions),那么在使用Session_start()之前浏览器不能有任何输出,否则会发生以下错误:
Warning: Cannot send session cache limiter - headers already sent (output started at /usr/local/apache/htdocs/cga/member/1.php:2)…………
你可以在php.ini里启动session.auto_start=1,这样就无需每次使用session之前都要调用session_start()。但启用该选项也有一些限制,如果确实启用了 session.auto_start,则不能将对象放入会话中,因为类定义必须在启动会话之前加载以在会话中重建对象。
请求结束后所有注册的变量都会被序列化。已注册但未定义的变量被标记为未定义。在之后的访问中这些变量也未被会话模块定义,除非用户以后定义它们。
警告: 有些类型的数据不能被序列化因此也就不能保存在会话中。包括 resource 变量或者有循环引用的对象(即某对象将一个指向自己的引用传递给另一个对象)。
●注册SESSION变量 :
PHP5使用$_SESSION[‘xxx’]=xxx注册SESSION全局变量。和GET,POST,COOKIE的使用方法相似。
注意:session_register(),session_unregister ,session_is_registered在php5下不再使用,除非在php.ini里把register_globle设为on,不过出于安全考虑,强烈建议关闭register_globle。HTTP_SESSION_VARS也不提倡使用了,官方建议用$_SESSION代替之。例如:
Page1.php
Session_start(); //使用SESSION前必须调用该函数。 $_SESSION[‘name’]=”我是黑旋风李逵!”; //注册一个SESSION变量 $_SESSION[‘passwd’]=”mynameislikui”; $_SESSION[‘time’]=time(); echo '<br /><a href="page2.php">通过COOKIE传递SESSION</a>'; //如果客户端支持cookie,可通过该链接传递session到下一页。 echo '<br /><a href="page2.php?' . SID . '">通过URL传递SESSION</a>';//客户端不支持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 /><a href="page1.php">返回山一页</a>';
有两种方法传递一个会话 ID:
cookie
URL 参数
会话模块支持这两种方法。cookie 更优化,但由于不总是可用,也提供替代的方法。第二种方法直接将会话 ID 嵌入到 URL 中间去。
PHP 可以透明地转换连接。除非是使用 PHP 4.2 或更新版本,需要手工在编译 PHP 时激活。在 Unix 下,用 --enable-trans-sid 配置选项。如果此配置选项和运行时选项 session.use_trans_sid 都被激活(修改php.ini),相对 URI 将被自动修改为包含会话 ID。
●session_id
session_id() 用于设定或取得当前session_id。php5中既可以使用session_id(),也可以通过附加在url上的SID取得当前会话的session_id和session_name。
如果session_id()有具体指定值的话,将取代当前的session_id值。使用该函数前必须启动会话:session_start();
当我们使用session cookies时,如果指定了一个session_id()值,每次启动session_start()都会往客户端发送一个cookie值。不论当前session_id是否与指定值相等。
session_id()如果没有指定值,则返回当前session_id();当前会话没有启动的话,则返回空字符串。
●检查session是否存在?
在以往的php版本中通常使用session_is_register()检查session是否存在,如果您使用$_SESSION[‘XXX’]=XXX来注册会话变量,则session_is_register()函数不再起作用。你可以使用
isset($_SESSION[‘xxx’])来替代。
● 更改session_id session_regenerate_id() 更改成功则返回true,失败则返回false。
使用该函数可以为当前session更改session_id,但不改变当前session的其他信息。例如:
<?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()返回当前session的name或改变当前session的name。如果要改变当前session的name,必须在session_start()之前调用该函数。注意:session_name不能只由数字组成,它至少包含一个字母。否则会在每时每刻都生成一个新的session id.
session改名示例:
<?php $previous_name = session_name("WebsiteID"); echo "新的session名为: $previous_name<br />"; ?>
●如何删除session?
1、unset ($_SESSION['xxx'])删除单个session,unset($_SESSION['xxx']) 用来unregister一个已注册的session变量。其作用和session_unregister()相同。 session_unregister()在PHP5中不再使用,可将之打入冷宫。
unset($_SESSION) 此函数千万不可使用,它会将全局变量$_SESSION销毁,而且还没有可行的办法将其恢复。用户也不再可以注册$_SESSION变量。
2、$_SESSION=array()删除多个session
3、session_destroy()结束当前的会话,并清空会话中的所有资源。。该函数不会unset(释放)和当前session相关的全局变量(globalvariables),也不会删除客户端的session cookie.PHP默认的session是基于cookie的,如果要删除cookie的话,必须借助setcookie()函数。
返回值:布尔值。
功能说明:这个函数结束当前的session,此函数没有参数,且返回值均为true
session_unset() 如果使用了$_SESSION,则该函数不再起作用。由于PHP5必定要使用$_SESSION,所以此函数可以打入冷宫了。
下面是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的步骤:
①session_start()
②$_SESSION=array()/unset($_SESSION['xxx'])
③session_destroy()
● SESSION security:
The session module cannot guarantee that the information stored in the session can only be seen by the user who created the session. Depending on the data it houses, more steps need to be taken to proactively protect the integrity of the session.
Evaluating the data carried in a session and implementing additional protection measures often comes at a cost and reduces user convenience. For example, if you want to protect users from simple social policies (note: the session ID displayed in the URL will be seen by others on the computer screen, or obtained by other websites through HTTP Referer, etc.), you should enable it. session.use_only_cookies. In this case, the client must unconditionally enable cookies, otherwise the session will not work.
There are several ways to leak existing session IDs to third parties. A leaked session ID enables a third party to access all resources associated with the specified ID. First, the URL carries the session ID. If you connect to an external site, the URL containing the session ID may be stored in the external site's Referer log. Second, a more active attacker may listen to packets on the network segment. If unencrypted, the session ID flows across the network in clear text. The solution to this is to implement SSL on the server and force users to use it.
By default, all data related to a specific session is stored in a file in the directory specified by the INI option session.save_path. One file is created for each session (regardless of whether there is data associated with that session). This is because a file is created every time a session is opened, regardless of whether data is written to the file. Note that due to limitations in working with the file system, this behavior has a side effect, which may cause user-customized session handlers (such as using database) to lose sessions that do not store data.
The functions introduced above will be used below, but there are also some functions related to session that are also introduced:
session_encode
Function function: session information encoding
Function prototype: string session_encode(void);
Return value: String
Function description: The returned string contains the name and value of each variable in the global variable, in the form: a|s:12:"it is a test";c|s:4:"lala"; a is the variable name s:12 represents the value of variable a "it is a The length of test is 12 and the variables are separated by semicolon ";".
session_decode
Function: decode session information
Function prototype: boolean session_decode (string data)
Return value: Boolean value
Function description: This function can decode session information, and returns a logical value if successful true
Php5 no longer uses session_id, but turns it into a constant SID and saves it in a cookie. If the client disables cookies, php will automatically pass the SID through the url automatically, and the condition is to set php.ini session.use_trans_sid = 1. At this time, it doesn’t matter even if the client disables cookies.
Use strip_tags() to output the SID to avoid XSS-related attacks.
Session跨页传递问题:
session跨页传递需要考虑三种情况:
①客户端禁用了cookie。
②浏览器出现问题,暂时无法存取cookie
③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(); $url="<a href="."\"s2.php?s=".$sn."\">下一页</a>"; //PHP5定义了一个常量SID来表示session_id(),$url还可以写成$url='<a href="page2.php?' . SID . '">下一页</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 "未登录,无权访问";
推荐学习:《PHP视频教程》
The above is the detailed content of One trick to solve PHP5 notes (COOKIE and SESSION) (share). For more information, please follow other related articles on the PHP Chinese website!