PHP Session Control session, Cookie Introduction

Source: Internet
Author: User
Tags php session setcookie

A. Cookies

1>cookie Introduction

Cookies are data stored in the client browser and can be used to track and store user data through cookies. In general, cookies are returned from the server to the client via Httpheaders. Most Web programs support the operation of cookies, because cookies are in the header of HTTP.
In PHP, the cookie is set by the Setcookie function, and any cookie,php sent back from the browser will automatically store it in

_cookie[' key ') to read a COOKIE value.
When using session sessions, a cookie is typically used to store the session ID to identify the user, the cookie has an expiration date, and the cookie is automatically deleted from the client after the validity period expires.

2> Setting cookies
Setcookie ()
Meaning: Used to set the cookie, in the Setcookie () function one has 7 parameters (only 5 commonly used parameters).
Syntax: Setcookie (name,value,expire,path,domain,secure,httponly)
Return value: If an output exists before this function is called, Setcookie () will fail and return false. If Setcookie () runs successfully, it returns true. This does not indicate whether the user has accepted the cookie.

Parameters:
Name
The name of the COOKIE, accessed through $_cookie[' name ').
Value
The value of the cookie
Expire
The time at which the cookie expires. This is a Unix timestamp, in seconds. You can set it up with the time () function plus the number of seconds you want it to expire. Or you can use Mktime (). If set to 0 or omitted, the cookie expires at the end of the session (when the browser is closed) and defaults to 0.
Path
(valid path) if the path is set to '/', the entire site is valid, and if set to '/foo/', then the cookie will only be available in the/foo/directory and all subdirectories (such as/foo/bar/of).
Domain
(the domain that the cookie is available in) is valid for the entire domain name, and to make the cookie available to the entire domain (including all its subdomains), simply set the value to the domain name (' example.com ' in this case).
Secure
Indicates that the cookie can only be transmitted through a secure HTTPS connection to the client. When set to true, cookies are set only if there is a secure connection. On the server side, the programmer can only send this cookie on a secure connection (eg: relative to

Value, Time () +3600, "path/", "baidu.com"); Set path and domain

3>cookie deletion and Expiration time
Instead of specifying a function to delete a cookie in PHP, the cookie is automatically invalidated by setting the cookie's expiration time to the current time before it reaches the deleted cookie.

4> to determine if a cookie is empty
Isset ()
Meaning: Determine whether a cookie exists.
Syntax: isset (the corresponding cookie attribute);
return value: True/false

Setcookie ("name", "SYN"), if (Isset ($_cookie["name")) {    echo  $_cookie["name"];} else{    echo "does not exist";}

The similarities and differences between session and Cookie

Cookies:
1, the data stored in the client, establish a user-server connection, usually can solve a lot of problems, but the cookie still has some limitations:
2, the cookie is relatively not too safe, easy to be compromised to cause cookie spoofing
3, the maximum value of a single cookie can only be stored 4k
4, each request must carry on the network transmission, occupies the bandwidth

Session
1, the user's session data stored on the server, no size limit,
2, through a session_id user identification, PHP by default, the session ID is saved through a cookie

Start using Sessionsession_start ();//Set a session$_session[' Test ' = time ();//Display the current Session_idecho "session_id:". Session_ ID (); echo "<br>";//Read SESSION value echo $_session[' test '];//destroy a sessionunset ($_session[' test '); echo "<br>" ; Var_dump ($_session);

Second, Session

1>session use

First execute the Session_Start method to open session, and then through the global variable $_session session read and write. 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. It can be stored in the form of a cache or a database to solve this problem.
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);

2> Delete and destroy session

Unset ()
When PHP uses the unset function to delete a session value, it is removed from the global variable $_session and cannot be accessed.

Session_Start (); $_session[' name '] = ' jobs '; unset ($_session[' name '); Echo $_session[' name ']; Hint name does not exist

Session_destroy ()
The Session_destroy function deletes all data, but session_id still exists.

Session_Start (); $_session[' name '] = ' jobs '; $_session[' time ' = time (); Session_destroy ();

Special attention:
Session_destroy () does not immediately destroy global variables

_session is empty, so if you need to destroy $_session immediately, you can use Unset ().

3> use session to store user's login information

Login information can be stored in the Sessioin, or stored in a 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.

<?phpsession_start ();//Assume that the user logged in successfully obtained the following user data $userinfo = array (' uid ' = ' = '  1011,    ' name ' = ' spark ',    ' email ' = ' 1637167XX@qq.com ',    ' sex '  = ' F '); 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 */$str =serialize ($userinfo); Serialization of user Information Setcookie (' UserInfo ', $str);

Learn more about serialization serialize;

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.