Summary of problem methods in cookie use

Source: Internet
Author: User
Tags http cookie http request parent directory set cookie setcookie

One, what is a cookie?

cookies are generated by the server side, always stored in a small piece of text information on the client, when you browse the Web page, the browser will store it on the hard disk, the next time you visit the same address, as long as the cookie is not invalidated, The browser sends its information to the server again.

Therefore, cookies are accompanied by a user request and the page is passed between the Web server and the browser. The cookie contains information that the server can read each time the user accesses the site.

Second, the cookie solves what problem?

Solves the problem that the information cannot be shared when the same browser accesses different Web pages. Why, then? Because the HTTP protocol is stateless, the Web server cannot differentiate between multiple requests made by the same browser. Cookies solve this problem.

How does a cookie interact?

The client interacts with the server side through the HTTP response header and the request header.

For example: Take 360 account Login For example, when Landing 360 User Center, will write cookie to yunpan.cn this domain. Let's open fiddle to see how the server wrote the yunpan.cn in the rain.

   

As can be seen from the image above, the server-side cookies are sent to the client via the HTTP response header, and each time a write action produces a Set-cookie response header, and the browser takes the response header to accept the cookie's

Now we are going to visit the yunpan.cn domain, we found that we did not enter the username and password, the direct landing. Again, we use Fillder to look at the exact process.

From the image above, we see that the value of the cookie is sent to the server in the HTTP request header.

Four, the cookie parameter and its meaning

Parameters Meaning Take value Note
name=<value>[name =< value ";] Name indicates the key of the cookie Value representing key Stored value must be escaped, generally with encodeuricompoment to escape, the key to the legality of must also be checked
[; Expires=<date>] The expiration date of the cookie, GMT is the standard for MS units The default is null, the cookie can only be used by the browser's
[; Domain=<domain>] Domain name in effect Domain name You can default to the domain name of the current page
[; Path=<path>] Path in effect /path You can default to the directory where the current Web page resides, and the cookie cannot be accessed across path, but you can access cookies to the parent directory settings
[; secure] Security True/false You can default to indicate that a cookie can only be passed to the server side for session validation in an HTTPS link, and HTTP does not pass that information.

The difference of cookies in different browsers

Categories of Browsers Maximum number of single domain cookies Maximum capacity of a single cookie Total caps for cookies Description
Ket 50 4095 4095 When the number of cookies exceeds, it will kick out the previous generated cookie and save the value of the latest cookie.
Ie7 50 4095 4095 Ditto
Ie8 50 4095 4095 Ditto
Ie9 150 4095 4095 Ditto
firefox12 150 4097 4097 Ditto
Chrome17 160~170 4097 4097 Ditto
Safari No restrictions 4097 4097

What can you do with cookies?

(1) Save the user's login status, such as in the above example, the user landing, the successful landing, the server generated a specific cookie returned to the client, the next time the client access to the domain name of any page, the cookie information sent to the server, the server has been tested,

To determine whether the user logged in.

(2) record the user's behavior, for example, Jingdong Mall in the lower left corner has a recent visit to the product record information, Dangdang has you recently browsed book information, are based on user access to the page, recorded to the cookie information to make.

(3) The dealer Shopping cart processing, because in the different page, clicks adds to the shopping cart, this information also is credited to the cookie inside. When the checkout is submitted uniformly

(4) custom page. If the site provides a skin-changing function, we will also record him in the cookie at this time so that the next visit or the original style page.

Seven, the security of cookies

Cookies are unsafe because they can be tampered with by the user. And because cookies store a lot of information, once that information leaks out, it is also very harmful, so we should use cookies carefully

JS Cookie Access

The code is as follows Copy Code

<script>

Write cookies function Author: Zhangkai
function Setcookie (name,value)//two parameters, one is the name of the cookie, one is the value
{
var days = 30; This cookie will be saved for 30 days
var exp = new Date (); New Date ("December 31, 9998");
Exp.settime (Exp.gettime () + days*24*60*60*1000);
Document.cookie = name + "=" + Escape (value) + "expires=" + exp.togmtstring ();
}
function GetCookie (name)//Fetch cookies functions
{
var arr = Document.cookie.match (New RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"));
if (arr!= null) return unescape (arr[2)); return null;

}
function Delcookie (name)//Delete cookie
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval=getcookie (name);
if (cval!=null) document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}

Setcookie ("Xiaoqi", "3")
Alert (GetCookie (' Xiaoqi '));
</script>

A very useful JavaScript read-write cookie function

A very useful JavaScript read-write cookie function

The code is as follows Copy Code

function Getcookieval (offset)
Get the value of the cookie after decoding
{
var endstr = documents.cookie.indexOf (";", offset);
if (endstr = = 1)
Endstr = Documents.cookie.length;
Return unescape (documents.cookie.substring (offset, endstr));
}
function Setcookie (name, value)
Set cookie Value
{
var expdate = new Date ();
var argv = setcookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2)? ARGV[2]: null;
var path = (argc > 3)? ARGV[3]: null;
var domain = (argc > 4)? ARGV[4]: null;
var secure = (argc > 5)? ARGV[5]: false;
if (expires!=null) Expdate.settime (Expdate.gettime () + (expires * 1000));
Documents.cookie = name + "=" + Escape (value) + ((expires = null)?  ""  :  ("; Expires= "+ expdate.togmtstring ()))
+ ((path = null)?  ""  :  (";  Path= "+ path") + ((domain = null)?  ""  :  ("; domain= "+ domain)"
+ (Secure = = True)?  "; Secure ":" ");
}
function Delcookie (name)
Delete Cookies
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval = GetCookie (name);
Documents.cookie = name + "=" + Cval + "; Expires= "+ exp.togmtstring ();
}
function GetCookie (name)
Get the original value of the cookie
{
var arg = name + "=";
var alen = Arg.length;
var clen = documents.cookie.length;
var i = 0;
while (I < Clen)
{
var j = i + Alen;
if (Documents.cookie.substring (i, j) = arg)
Return Getcookieval (j);
i = Documents.cookie.indexOf ("", I) + 1;
if (i = = 0) break;
}
return null;
}

<script language= "JavaScript" >
<!--
function Openpopup () {
Url= "Popup.htm"
window.open ("gonggao.htm", "Gonggao", "Width=260,height=212,left=200,top=0")
}

function Get_cookie (Name) {
var search = Name + "="
var returnvalue = "";
if (Documents.cookie.length > 0) {
offset = documents.cookie.indexOf (search)
if (offset!=-1) {
Offset + = Search.length
End = Documents.cookie.indexOf (";", offset);
if (end = = 1)
end = Documents.cookie.length;
Returnvalue=unescape (documents.cookie.substring (offset, end))
}
}
Return returnvalue;
}

function Helpor_net () {
if (Get_cookie (' popped ') = = ") {
Openpopup ()
Documents.cookie= "Popped=yes"
}
}
Helpor_net ()
-->
</SCRIPT>


If the point is OK, as long as the cookie is not clear, later access will not be prompted, if not the point of determination will be prompted each time. In the JS file, the whole station contains

The code is as follows Copy Code
<script language= "JavaScript" >
<!--
var the_cookie = Document.cookie;
var Broken_cookie = The_cookie.split (":");
var the_visiteraccepted = unescape (broken_cookie[1]);
//
if (the_visiteraccepted== "undefined") {
var tmp=confirm (' When and where ' Chinese people. ');
if (Tmp==false) {
Window.close ();
}else{
var the_visiteraccepted = 1;
var The_cookie = "ilovechina=visiteraccepted:" + Escape (the_visiteraccepted);
Document.cookie = The_cookie;
}
}
-->
</SCRIPT>

Cookie usage in PHP


The Setcookie () function sends an HTTP cookie to the client.

A cookie is a variable that is sent by the server to the browser. Cookies are usually small text files that the server embeds into the user's computer. This cookie is sent whenever the computer requests a page through the browser.

The name of the cookie is specified as a variable of the same name. For example, if the cookie being sent is named "name", a variable named $user is automatically created, containing the value of the cookie.

The cookie must be assigned before any other output is sent.

If successful, the function returns True, otherwise it returns false.

Grammar
Setcookie (Name,value,expire,path,domain,secure)

*/

The code is as follows Copy Code

$cookieinfo =session_get_cookie_params (); Get cookie Information
if (Empty ($cookieinfo [' domain ']) && (Empty ($cookieinfo [' secure '))]//Check whether the result is empty
{
Setcookie (Session_name (), ", Time () -3600, $cookieinfo [' path ']); Set cookies
}
ElseIf (Empty ($cookieinfo [' secure '])]/check option is empty
{
Setcookie (Session_name (), ', Time () -3600, $cookieinfo [' Path '], $cookieinfo [' domain ']); Set cookies
}
Else
{
Setcookie (Session_name (), ', Time () -3600, $cookieinfo [' Path '], $cookieinfo [' Domain '], $cookieinfo [' secure ']); Set cookies
}
Session_destroy (); Logout session
Print_r ($_session);
Print_r ($_cookie);

Using Session_set_cookie

_params can set the lifetime and path

Session_set_cookie_params (0, '/yourpath/'); Set the lifetime and path of a cookie


/*

Note: You can access the value of a cookie named "User" by $http _cookie_vars["user" or $_cookie["user".

Note: When you send a cookie, the value of the cookie is automatically URL-coded. The URL is decoded when it is received. If you do not need this, you can use Setrawcookie () instead.

*/

For more details please see: http://www.111cn.net/phper/php/36583.htm

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.