The PHP session control cookie and the session full parsing

Source: Internet
Author: User
Tags http cookie session id php session setcookie

Cookie Introduction

Cookies are data stored in the client's browser , and we use cookies to track and store user data.

In general, cookies are returned from the server to the client via HTTP headers . Most Web programs support the operation of cookies because the cookie is in the header of HTTP, so it must be set before other information output, similar to the use limit of the header function.

PHP uses the setcookie function to set the COOKIE, and any cookie,php sent back from the browser will automatically store him in the global variable of $_cookie, so we can pass the $_ cookie[' key ') to read a cookie value.

Cookies in PHP are very widely used, often used to store users ' login information, shopping carts, etc., and often use cookies to store session IDs to identify users when using session sessions, and the cookie has an expiration date, The cookie is automatically removed from the client. Cookies can also set the domain and path for security control purposes.

setcookie(‘test‘, time());// 打开输出控制缓冲ob_start();print_r($_COOKIE// 复制缓冲区内容到$content中$content = ob_get_contents();$content = str_replace(" "‘&nbsp;‘$content);// 清空(擦掉)输出缓冲区ob_clean();header("content-type:text/html; charset=utf-8");echo‘当前的Cookie为:<br>‘;// nl2br 在字符串所有新行之前插入 HTML 换行标记 <br>echo nl2br($content);
Setcookie ()

The Setcookie () function sends an HTTP cookie to the client. A cookie is a variable that is sent to the browser by the server.

Note: The value of the COOKIE named "User" can be accessed by $_cookie["user".

Setrawcookie ()

PHP also has a function to set the cookie Setrawcookie

Setrawcookie is basically the same as Setcookie, the only difference is that the value is not automatically URL-encoded, so you need to do urlencode manually when needed.

setrawcookie(‘cookie_name‘, rawurlencode($valuetime()+60*60*24*365
Header ()

Because cookies are set by HTTP headers, they can also be set directly using the header method.

header("Set-Cookie:cookie_name=value");
Delete Cookies

Deleting cookies in PHP is also implemented using the Setcookie function.

Principle: Setting the expiration time of the cookie to the current time, the cookie will expire automatically, and the purpose of deleting cookies is achieved.

setcookie(‘test‘, ‘‘, time()-1)

You can also delete cookies directly from the header.

header("Set-Cookie:test=1393832059; expires=".gmdate(‘D, d M Y H:i:s \G\M\T‘, time()-1));
Valid path for cookies

The path in the cookie is used to control which path the cookie is set to, and the default is '/', which is available under all paths.

// 使test在/path以及子路径/path/abc下都有效,但是在根目录下就读取不到test的cookie值。setcookie(‘CookieName‘, ‘CookieValue‘, time() + 3600, ‘/path‘);
The similarities and differences between session and Cookie

Cookies store data on the client and establish a connection between the user and the server, which can often solve many problems, but the cookie still has some limitations:

    1. Cookies are relatively less secure and easily compromised to cause cookie spoofing

    2. The value of a single cookie can be stored up to 4k, and each request is transmitted over the network, consuming bandwidth

    3. User information can be stored in the Sessioin, but also stored in the cookie, the difference between them is that the session can easily access a variety of data types, and the cookie only supports string type, while for some security relatively high data, Cookies need to be formatted and encrypted, and session storage is more secure on the server side.

Session Introduction

Session data is stored on the server side , with no size limit

With a session_id user identification, PHP by default the session ID is saved through a cookie, so in a way, seesion relies on cookies.

But this is not absolute, the session ID can also be implemented by parameters, as long as the session ID can be passed to the server to identify the mechanism can use the session.

//Create a session  session_start (); $_session  [ ' sessionname ' ] =  Sessionvalue ' ; echo   "session_id:" . session_id (); //displays the current session_id  echo   "<br>" ; //reads the value of Session  echo  $_session  [ ' sessionname ' ]; //destroys a session  unset  ($_session  [ ' sessionname ' ]); echo   var_dump ($_ SESSION ); 

The session automatically encode and decode the values to be set, so the session can support any data type , including data and objects.

session_start();$_SESSION[‘ary‘array(‘name‘‘jobs‘);$_SESSION[‘obj‘new stdClass();var_dump($_SESSION);// unset($_SESSION[‘ary‘]);// unset($_SESSION[‘obj‘]);
Delete session

Deleting a session value can use the unset () function

If you want to delete all the sessions, you can use the Session_destroy () function, but session_id still exists.

It is important to note that Session_destroy () does not immediately destroy global variables S E S S I ON inof thevalue,onlyhave awhenunderTimesagainVisitAskof thewhenHou, _session is empty, so if you need to destroy $_session immediately, you can use the unset function. Extended:

By default, the session is stored as a file on the server, so when a page opens the session, it will monopolize the session file, which will cause other concurrent accesses of the current user to be unable to execute and wait. Can be stored in the form of a cache or a database to solve this problem

If you need to destroy session_id, which is usually used when the user exits, you also need to explicitly call the Setcookie method to remove the session_id cookie value.

Comprehensive case-Store user's login information
//Create sessionSession_Start ();//Assume that the user logged in successfully obtained the following user data$userinfo=Array(' uid '=10000,' name '=' Spark ',' Email '=' [email protected] ',' Sex '=' man ',' age '=' + '); Header ("content-type:text/html; Charset=utf-8 ");//Save user information to session$_session[' uid '] =$userinfo[' uid '];$_session[' name '] =$userinfo[' name '];$_session[' UserInfo '] =$userinfo;//A simple way to save user data to a cookie--encryption$secureKey=' Imooc ';//Encryption Key$str= Serialize ($userinfo);//Serialization of user information$str= Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, MD5 ($secureKey),$str, MCRYPT_MODE_ECB));Echo "Encrypted user information:<br>";p Rint_r ($str.' <br> ');//Store encrypted user data in a cookieSetcookie (' UserInfo ',$str);//When need to be used--decrypt$str= Mcrypt_decrypt (mcrypt_rijndael_256, MD5 ($secureKey), Base64_decode ($str), MCRYPT_MODE_ECB);$uinfo= Unserialize ($str);Echo "Decrypted user information:<br>";p Rint_r ($uinfo);

Cookie/session mechanism Detailed: http://blog.csdn.net/fangaoxin/article/details/6952954

The PHP session control cookie and the session full parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.