PHP session and Cookie usage Instructions _php tutorial

Source: Internet
Author: User
Tags http cookie php session php print setcookie
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 (Stringname [, stringvalue [, int expire [, Stringpath [, Stringdomain [, BOOL secure [, BOOL HttpOnly]]] ] )
Name:cookie variable name Value:cookie The value of the variable expire: the end of the validity period,
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:
Copy CodeThe code is as follows:
$value = ' something from somewhere ';
Setcookie ("TestCookie", $value);
/* Simple cookie setting */setcookie ("TestCookie", $value, Time () +3600); /* Valid for 1 hours */setcookie ("TestCookie", $value, Time () +3600, "/~rasmus/", ". example.com", 1); /* Valid directory/~rasmus, valid domain name example.com and all sub-domains */
?>

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:
Copy CodeThe code is as follows:
$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 automatically escape 3) when used, 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-revalidate, post-check=0, pre-check=0
Pragma:no-cache
Content-type:text/html

This line implements the Cookie function, received after the 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. 2.1 SessionID Transfer 2.1.1 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
Copy CodeThe code is as follows:
page1.php
Session_Start ();
Echo ' Welcome to page #1 ';
/* Create session variable and assign value to session variable */$_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 ';
/*
By default php5.2.1, the SID will have a value only if the cookie is written, if the session
The corresponding cookie already exists, then the SID will be (undefined) empty */
?>

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?>

2.5 Session in PHP large Web application for large access sites, with 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 (Callbackopen, Callbackclose, Callbackread, Callbackwrite, Callbackdestroy, CALLBACKGC) provide us with solutions to 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 () uses this function 4 when loading session data from storage. 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 () for garbage collection of data in the storage system, see the PHP manual Session_set_save_handler () function.
If you use a class to process, use 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. STRINGSESSION_ID () ID of the current session
Stringsession_name () The name of the session currently accessed, which is the cookie name where the client holds the session ID. Default PHPSESSID. Arraysession_get_cookie_params () The details of the session associated with this session.
Stringsession_cache_limiter () controls client cache INI Session_cache_expire () control client cache time for pages using session bool Session_destroy () Delete server-side save session information file void session_set_cookie_params (int lifetime [, Stringpath [, Stringdomain [, BOOL secure [, BOOL HTTP Only]]) set the details of the session associated with this session bool Session_set_save_handler (Callbackopen, Callbackclose, Callbackread, Callbackwrite, Callbackdestroy, CALLBACKGC) define the function that handles the session (not the default way)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns a new session ID


2.7 session security The attacker could be able to have the same capabilities as the user in the system by investing a lot of effort in trying to get the valid session ID of the existing user, with the session ID.
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 '];
}

/* If the user SESSION ID is forged */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 /**
* Validity of the session
*/functionsessionverify () {
if (!isset ($_session[' user_agent ')) {
$_session[' user_agent ' = MD5 ($_server[' remote_addr ')
. $_server[' http_user_agent ');
}
/* If the user session ID is forged, reassign session ID */elseif ($_session[' user_agent ']! = MD5 ($_server[' remote_addr ')
. $_server[' Http_user_agent ')) {
SESSION_REGENERATE_ID ();
}
}

/**
* Destroy session
* Three steps to achieve the perfect, not leak *
*/functionsessiondestroy () {
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

http://www.bkjia.com/PHPjc/321607.html www.bkjia.com true http://www.bkjia.com/PHPjc/321607.html techarticle 1. PHP's Cookie cookie is a mechanism for storing data on a remote browser to track and identify users. PHP sends a cookie in the header message of the HTTP protocol, so the Setcookie () function must ...

  • 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.