PHP session and cookie instructions

  • 2020-03-31 20:32:12
  • OfStack

1. PHP cookies

Cookies are a mechanism for storing data on the remote browser side to track and identify users. PHP sends cookies in HTTP headers, so the setcookie() function must be called before any other information is exported to the browser, similar to the restriction on the header() function. 1.1 setting cookies:
Cookies can be set using the setcookie() or setrawcookie() functions. You can also set this by sending the HTTP header 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 value: the value of the cookie variable expires:
Path: valid directory,
Domain: valid domain, top-level domain unique secure: if the value is 1, the cookie will only be valid on HTTPS connections, if the default value is 0, HTTP and HTTPS will work.
Example:
 
<?php 
$value= 'something from somewhere'; 
setcookie("TestCookie", $value); 
setcookie("TestCookie", $value, time()+3600); setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); /*  Effective directory /~rasmus, Valid domain name example.com And all of its subdomains */ 
?> 

Set multiple cookie variables: setcookie('var[a]','value'); An array is used to represent a variable, but its index is not quoted. This allows the COOKIE variable to be read using $_COOKIE[' var'][' a'].

1.1.2. Use header() to set cookie;
The header (" Set - cookies: name = $value [path = $path [; domain=xxx.com [;]] ");
The following arguments are the same as those listed above for the setcookie function.
Such as:
 
$value= 'something from somewhere'; 
header("Set-Cookie:name=$value"); 

1.2 Cookie reading:

You can read browser-side cookies directly using PHP's built-in super global variable $_COOKIE.
The cookie"TestCookie" was set in the above example, now we will read:

Print $_COOKIE [' TestCookie];

Is the COOKIE output? !

1.3 delete the cookie
Simply set the effective time to less than the current time and set the value to null. For example:
Setcookie (" name ", "", time () - 1);
Header () is similar.

1.4 frequently asked questions:

1) with setcookie () there is error, may be because the call setcookie () in front of the output or Spaces. May your document from other character set conversion to come over, the back of the document may have BOM signature (that is, in the file content to add some hidden BOM character). The solution is to make your documents do not appear this kind of circumstance. And by using ob_start () function can deal with.
2) $_COOKIE may be automatically escaped under the influence of magic_quotes_gpc
< ! - [if! SupportLineBreakNewLine] - >

1.5 cookie working mechanism:

Some learners are impulsive and don't have the heart to study the principle, so I put it in the back.
A) the server sets a Cookie in the client by sending an HTTP set-cookie header along with the response.
B) the client automatically sends an HTTP cookie header to the server and the server receives the read.

HTTP / 1 x 200 OK
X - Powered By: PHP / 5.2.1
The Set - cookies: TestCookie = something from somewhere; Path = /
Expires: Thu, 19 Nov 2007 18:52:00 GMT
Cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no cache
The content-type: text/HTML

This line implements the cookie function, after receiving this line Set- cookie: TestCookie=something from somewhere; Path = /
The browser creates a cookie on the client's disk and writes:

TestCookie = something from somewhere.
This line is that we use setcookie('TestCookie','something from somewhere','/'); Header (' set-cookie: TestCookie=something from somewhere; Path = / '); Results.
< ! -- [endif] -- >



2. The PHP Session

Cookie session using the expiration time is set to 0, and calls a session ID unique identifier (a long string of a string), synchronous generate some session files on the server side (can define your own session save the type), link up with the user authority. Web applications store data associated with the session, and let the data as the user passed between pages.

Visitors to the site are assigned a unique identifier, called a session ID. It is either stored in the client's cookie or passed through the URL. Session support allows the user to register any number of variables and reserve them for each request. When a visitor visits a site, PHP automatically checks whether a specific session ID has been sent in the request (if session.auto_start is set to 1) or when the user requests (explicitly called by session_start() or implicitly called by session_register()). If so, the previously preserved environment is rebuilt. 2.1 transfer of sessionID 2.1.1 transfer of sessin ID by cookie

Using session_start() to invoke session, the server generates the session ID hash value and the session name with the default value of PHPSESSID when generating the session file, and sends the variable PHPSESSID(session name) with the value of a 128-bit hash value to the client. The server will interact with the client through this cookie.
The value of the session variable is serialized internally in PHP and stored in a text file on the server machine, interacting with the client's coolie where the variable name is PHPSESSID by default.
The server automatically sends the HTTP header :header(' set-cookie: session_name()=session_id(); Path = / ');
Setcookie (session_name (), session_id ());
When you jump from the page to a new page and call session_start(),PHP checks the server-side session data associated with the given ID and creates a new data set if it is not found.

2.1.2 pass the session ID through the URL
This method is only used if the user has forbidden the use of cookies, because browser cookies are already common and should not be used for security reasons.
< A href = "p.p HP? < ? PHP print session_name ()? > = < ? PHP print session_id ()? >" > Xxx< / a> , you can also pass the session value through POST.

2.2 instance of session basic usage
 
<?php 
// page1.php 
session_start(); 
echo'Welcome to page #1'; 
$_SESSION['favcolor'] = 'green'; 
$_SESSION['animal'] = 'cat'; 
$_SESSION['time'] = time(); 

//If the client USES a cookie, you can pass the session directly to page2.php
echo'<br /><a href="page2.php">page 2</a>'; 

//If the client disables cookies
echo'<br /><a href="page2.php?' . SID . '">page 2</a>'; 
 
?> 

<?php 
// page2.php 
session_start(); 
print$_SESSION['animal']; //Print out a single session
var_dump($_SESSION); //Print out the session value passed from page1.php
?> 


2.3 use the session function to control page caching.
In many cases, we need to determine whether our web pages are cached on the client side, or to set the effective time of the cache. For example, there is some sensitive content on our web page and we need to log in to view it. If the cache is local, we can directly open the local cache and browse to the web page without logging in.

Use session_cache_limiter (' private '); Page client caching can be controlled and must be invoked before session_start().
See http://blog.chinaunix.net/u/27731/showart.php? for more parameters Client side cache control for id=258087.
Controls client cache time with session_cache_expire(int); Unit (s). Is also called before session_start().

This is just a way to control the cache in the case of session, and we can also control the cache of the page in header().

2.4 delete the session

It takes three steps.
< ? PHP
Session_destroy (); // first step: delete the server-side session file, which USES the setcookie(session_name(), ",time()-3600); // step 2: delete the actual session:
The $_SESSION = array (); // step 3: delete $_SESSION global variable array? >

2.5 use of session in PHP large web applications for sites with large traffic, the default session storage method is not suitable, currently the best method is to use the database access session. At this time, the function bool session_set_save_handler(callbackopen, callbackclose, callbackread, callbackwrite, callbackdestroy, Callbackgc) is the solution to this problem.
The six functions used by this function are as follows:

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

2. Bool close() closes the session storage operation.

3. Mixde read() USES this function when loading session data from the store. 4. Bool write() writes all data for a given session ID to the store. 5. Bool destroy() destroys data associated with the specified session ID.
If you are using a class, use the session_set_save_handler(
Array (' className ', 'open'),
Array (' className ', 'close'),
Array (' className ', 'read'),
Array (' className ', 'write'),
Array (' className ', 'destroy'),
Array (' className ', 'the gc),
)
Call the six static methods in the className class. Classnames can be exchanged for objects without calling static methods, but static members do better than generating objects.

2.6 commonly used session function:

Bool session_start (void); Initialize the session
Bool session_destroy(void): removes the server-side session association file. Stringsession_id () the id of the current session
Stringsession_name () the session name currently accessed, that is, the cookie name of the session ID held by the client. Arraysession_get_cookie_params () details of the session associated with this session.
Stringsession_cache_limiter () controls the client cache of the page that USES session ini session_cache_expire() controls the client cache time bool session_destroy() removes the server file that holds session information void session_set_cookie_params(int lifetime [, stringpath [, Stringdomain [, bool secure [, bool httponly]]]]) sets the session details associated with this session bool session_set_save_handler(callbackopen, callbackclose, callbackread, callbackwrite, callbackdestroy, Callbackgc) defines a function that handles sessions (not in the default way)
Bool session_regenerate_id([bool delete_old_session]) assigns a new session id


2.7 session security issues attackers put a lot of effort into trying to obtain the valid session ID of the existing user. With the session ID, they may be able to have the same ability as this user in the system.
Therefore, our main solution is to validate the validity of session ID.
< ? PHP

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 ();
}
? >


2.8 the difference between Session passed by cookie and passed by SID:
In the case of the default configuration of php5.2.1 session, when the session is generated, the server side will generate the predefined super global variable SID while sending the header set-cookie (that is, it is equivalent to writing the cookie and throwing the SID). When the $_COOKIE['PHPSESSID'] exists, the cookie will not be written and the super global variable SID will not be generated. At this time, the SID will be empty.


2.9 session usage instance < ? PHP
FunctionsessionVerify () {
If (! Isset ($_SESSION [' user_agent '])) {
The $_SESSION [' user_agent] = MD5 ($_SERVER [' REMOTE_ADDR]
. $_SERVER [' HTTP_USER_AGENT ']);
}
Elseif ($_SESSION [' user_agent]! = the MD5 ($_SERVER [' REMOTE_ADDR]
. $_SERVER [' HTTP_USER_AGENT ']) {
Session_regenerate_id ();
}
}

FunctionsessionDestroy () {
Session_destroy ();
Setcookie (session_name (), ' 'time () - 3600);
The $_SESSION = array ();
}
? >

Note:

The session header has been sent for the same reason as the cookie.
In php5, all the registry configuration options for PHP sessions are programmatically configurable and generally do not need to be modified.
Session to save data, is through the serialization of $_SESSION array to store, so there is a serialization of the problem, there may be a special character value to use base64_encode function encoding, read the time with base64_decode decoding

Related articles: