PHP Cookie and Session analysis

Source: Internet
Author: User
Tags http cookie php print
PHP Cookie and Session analysis
1. PHP Cookies

A cookie is a mechanism for storing data on a remote browser to track and identify users.
PHP sends a cookie in the header of the HTTP protocol, so the Setcookie () function must be called before other information is exported to the browser, similar to the limit on the header () function.

1.1 Setting Cookies:
You can use the Setcookie () or Setrawcookie () function to set the cookie. It can also be set by sending HTTP headers directly to the client.
1.1.1 Use the Setcookie () function to set the cookie:
BOOL Setcookie (php?name=str "onclick=" Tagshow (event) "class=" T_tag ">string name [, php?name=str" onclick= "Tagshow ( Event) "class=" T_tag ">string value [, int expire [, php?name=str" onclick= "Tagshow (event)" class= "T_tag" >string path [, Php?name=str "onclick=" Tagshow (event) "class=" T_tag ">string domain [, bool secure [, BOOL HttpOnly]] []])
Name:cookie variable Name
The value of the Value:cookie variable
Expire: The time at which the validity period ends,
Path: Valid directory,
Domain: Valid domain name, top-level domain unique
Secure: If the value is 1, the cookie is valid only on HTTPS connections, and HTTP and HTTPS are available if the default value is 0.
Example:
$value = ' something from somewhere ';

Setcookie ("TestCookie", $value);
Setcookie ("TestCookie", $value, Time () +3600);
Setcookie ("TestCookie", $value, Time () +3600, "/~rasmus/", ". example.com", 1);
?>

Set multiple cookie variables: Setcookie (' var[a] ', ' value '), use an array to represent the variable, but his subscript is not quoted. This allows you to read the cookie variable with $_cookie[' var ' [' a '].

1.1.2. Setting a cookie using the header ();
Header ("Set-cookie:name= $value [;p ath= $path [;d omain=xxx.com[; ...]];
The following parameters are the same as those listed above for the Setcookie function.
Like what:

$value = ' something from somewhere ';
Header ("Set-cookie:name= $value");

1.2 Cookie read:

The browser-side cookie can be read directly with PHP's built-in Super global variable $_cookie.
The above example sets the cookie "TestCookie" and now we are reading:

Print $_cookie[' TestCookie '];

Is the cookie being exported?!

1.3 Deleting cookies
Just set the valid time to less than the current time, and leave the value blank. For example:
Setcookie ("name", "", Time ()-1);
Similar to the header ().

1.4 Frequently Asked questions resolved:

1) There is an error when using Setcookie (), possibly because there is an output or a space in front of the call to Setcookie (). It is also possible that your document will be converted from another character set, with a BOM signature behind the document (that is, adding some hidden BOM characters to the file contents). The solution is to keep your documents from happening. There is also a point that can be handled by using the Ob_start () function.
2) $_cookie affected by MAGIC_QUOTES_GPC, may be automatically escaped
3) When using, it is necessary to test whether the user supports cookies


1.5 Cookie working mechanism:

Some learners are more impulsive and have no mind to study the principle, so I put it back.
A) The server sets a cookie (more than one cookie) in the client computer by sending an HTTP Set-cookie header in response.
b) The client automatically sends an HTTP cookie header to the server and the server receives the read.

http/1.x OK
x-powered-by:php/5.2.1
Set-cookie:testcookie=something from somewhere; path=/
Expires:thu, 18:52:00 GMT
Cache-control:no-store, No-cache, Must-ridate, post-check=0, pre-check=0
Pragma:no-cache
Content-type:text/html

This line implements the cookie function, after receiving this row
Set-cookie:testcookie=something from somewhere; path=/
The browser creates a cookie file on the client's disk and writes it inside:

Testcookie=something from somewhere;
/

This line is the result of our use of Setcookie (' TestCookie ', ' Something from somewhere ', '/'); that is, with the header (' Set-cookie:testcookie=something from somewhere; path=/'); the result.




2. The session of PHP

The session uses a cookie that has an expiration time of 0, and a unique identifier called the session ID (a long string of strings), which generates some session files on the server side (you can define the save type of the session yourself). Connect with the user's office. The Web application stores the data associated with these sessions and lets the data pass along with the user across the page.

Visitors to the site are assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL.

Session support allows users to register any number of variables and keep them for use by individual requests. When a visitor visits a website, PHP automatically (if Session.auto_start is set to 1) or when the user requests (explicitly called by session_start () or Session_register () secretly calls) checks whether a specific session ID is sent in the request. If it is, the previously saved environment is rebuilt.

Transmission of 2.1 SessionID

2.1.1 Transfer sessin ID via cookie

Using Session_Start () Call session, the server side generates session ID hash value and the default value is PHPSESSID session name, and sends the variable to the client (default). PHPSESSID (session name), which is a 128-bit hash value. The server side will interact with the client through this cookie.
The value of the session variable is stored in a text file on the server machine after the internal serialization of PHP, and the client's variable name is PHPSESSID by default for the coolie of the corresponding interaction.
That is, the server automatically sends an HTTP header: header (' Set-cookie:session_name () =session_id (); path=/');
namely Setcookie (Session_name (), session_id ());
When a new page jumps from the page and calls Session_Start (), PHP checks the session data for the server-side storage associated with the given ID, and creates a new dataset if it is not found.

2.1.2 Sending session ID via URL
This method is only used when the user prohibits the use of cookies, as browser cookies are already common and are not available for security purposes.
= ">xxx can also pass the session value via post.

2.2 Session Basic Usage example

page1.php
Session_Start ();
Echo ' Welcome to page #1 ';

$_session[' favcolor '] = ' green ';
$_session[' animal ' = ' cat ';
$_session[' time ' = time ();

If the client uses cookies, it can pass the session directly to page2.php
Echo '
Page 2 ';

If the client disables cookies
Echo '
Page 2 ';

?>

page2.php
Session_Start ();
Print $_session[' animal ']; Print out a single session
Var_dump ($_session); Print out the session value passed by page1.php.
?>


2.3 Use the Session function to control page caching.
In many cases, we want to determine whether our web page is cached on the client, or to set the cache's effective time, such as some sensitive content on our web page and to log in to view, if cached locally, you can directly open the local cache can not log in and browse to the Web.

Use Session_cache_limiter (' private '); You can control the page client cache and must be called before Session_Start ().
For more parameters see http://blog.chinaunix.net/u/27731/showart.php?id=258087 client cache control.

Controls the client cache time with session_cache_expire (int), unit (s), and is also called before Session_Start ().

This is just a way to control the cache using the session, and we can also control the cache of the control page in the header ().
2.4 Delete Session
Be implemented in three steps.
Session_destroy (); The first step: Delete the server-side session file, which uses
Setcookie (Session_name (), ", Time ()-3600); Step two: Delete the actual session:
$_session = Array (); Step three: Delete the $_session global variable array
?>
The use of 2.5 session in PHP large Web applications
For sites with large access, the default session storage method is not suitable, the current optimal method is to use the database access session. At this point, the function bool Session_set_save_handler (callback open, callback Close, callback read, callback write, callback destroy, callback GC) are the solutions that are provided to us to solve this problem.
The 6 functions used by the function are as follows:

1. bool Open () is used to open the session storage mechanism,

2. BOOL Close () closes the session store operation.

3. Mixde read () Use this function when loading session data from storage

4. BOOL Write () writes all data for the given session ID to the store

5. bool Destroy () destroys data associated with the specified session ID

6. BOOL GC () garbage collection of data in the storage system

See the PHP manual Session_set_save_handler () function for examples.
If you use a class to process, use the
Session_set_save_handler (
Array (' ClassName ', ' open '),
Array (' ClassName ', ' close '),
Array (' ClassName ', ' read '),
Array (' ClassName ', ' write '),
Array (' ClassName ', ' destroy '),
Array (' ClassName ', ' GC '),
)
Call the 6 static methods in the ClassName class. ClassName you can swap objects without calling a static method, but using static members does not produce objects, and it performs better.
2.6 Commonly used session functions:

BOOL Session_Start (void); Initialize session
BOOL Session_destroy (void): Deletes the server-side session Association file.
String session_id () ID of the current session
String Session_name () the name of the session currently accessed, which is the cookie name where the client holds the session ID. Default PHPSESSID.
Array Session_get_cookie_params () the details of the session associated with this session.
String Session_cache_limiter () controls client-side caching of pages using session
INI session_cache_expire () controls client cache time
BOOL Session_destroy () Delete the server-side file that holds session information
void session_set_cookie_params (int lifetime [, String path [, string domain [, bool secure [, BOOL HttpOnly]]]) is set with this SE Details of the session associated with the Ssion
BOOL Session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, Callback G c) Define the function that handles the session (not by using the default method)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns a new session ID
2.7 Session security issues
By investing a lot of effort in trying to get the valid session ID of an existing user, with the session ID, they are likely to have the same capabilities as this user in the system.
Therefore, our main approach is to validate the validity of session ID.

if (!isset ($_session[' user_agent ')) {
$_session[' user_agent ' = $_server[' remote_addr '].$_server[' http_user_agent '];
}


ElseIf ($_session[' user_agent ']! = $_server[' remote_addr ']. $_server[' Http_user_agent '] {
SESSION_REGENERATE_ID ();
}
?>
The 2.8 session is passed through a cookie and is passed through the SID differently:
In the case of the default configuration of the php5.2.1 session, when the session is generated, the server side will generate a pre-defined super global variable SID at the same time that the header Set-cookie is sent (that is, the write cookie and the thrown SID are equivalent.), when the $ _cookie[' Phpsessid ' is present, the COOKIE will no longer be written, and the Super global variable SID will no longer be generated, at which time the SID is empty.
2.9 Session Usage Example


function Sessionverify () {
if (!isset ($_session[' user_agent ')) {
$_session[' user_agent ' = MD5 ($_server[' remote_addr ')
. $_server[' http_user_agent ');
}

ElseIf ($_session[' user_agent ']! = MD5 ($_server[' remote_addr ')
. $_server[' Http_user_agent ')) {
SESSION_REGENERATE_ID ();
}
}


function Sessiondestroy () {
Session_destroy ();
Setcookie (Session_name (), ", Time ()-3600);
$_session = Array ();
}
?>

Indicate:

The session header message has been sent for the same reason as the cookie.
In PhP5, the registry configuration options for all PHP sessions are programmable, and in general we do not need to modify their configuration. To learn about the session registry configuration options for PHP, refer to the session handler function at the manual.
Session of the time to save data, is serialized $_session array to storage, so there are serialization of problems, there may be a special character value to be encoded with the Base64_encode function, read the time and then use Base64_decode decoding
  • 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.