Home > Backend Development > PHP Tutorial > Instructions for using php session and cookies_PHP tutorial

Instructions for using php session and cookies_PHP tutorial

WBOY
Release: 2016-07-21 15:39:16
Original
808 people have browsed it

1. PHP's COOKIE

Cookie is a mechanism that stores data on the remote browser side and uses it to track and identify users. PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function. 1.1 Set cookies:
You can use the setcookie() or setrawcookie() function to set cookies. It can also be set by sending http headers directly to the client.
1.1.1 Use the setcookie() function to set cookies:
bool setcookie( stringname [, stringvalue [, int expire [, stringpath [, stringdomain [, bool secure [, bool httponly]]]]] )
name: cookie variable name value: value of cookie variable expire: end of validity period,
path: valid directory,
domain: valid domain name, top-level Domain unique secure: If the value is 1, the cookie is only valid on https connections, if it is the default value 0, both http and https are available.
Example:

Copy Code The code is as follows:

$value= 'something from somewhere';
setcookie("TestCookie", $value);
/* Simple cookie setting*/setcookie("TestCookie", $value, time()+3600); /* Validity period is 1 hour*/setcookie("TestCookie", $value, time()+3600, "/~ rasmus/", ".example.com", 1); /* Valid directory/~rasmus, valid domain name example.com and all its subdomains*/
?>

settings Multiple cookie variables: setcookie('var[a]','value'); Use an array to represent the variable, but its subscript does not need quotes. In this way, you can use $_COOKIE['var']['a'] Read the COOKIE variable.

1.1.2. Use header() to set cookie;
header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com [; ]]"); The parameters following
are the same as the parameters of the setcookie function listed above.
For example:
Copy the code The code is as follows :

$value= 'something from somewhere';
header("Set-Cookie:name=$value");

1.2 Cookie Reading:

You can directly use the PHP built-in super global variable $_COOKIE to read the cookies on the browser side.
In the above example, the cookie "TestCookie" is set, now let's read it Get:

print$_COOKIE['TestCookie'];

Has the COOKIE been output?!

1.3 Delete cookie
Just set the validity time to Less than the current time, and setting the value to empty. For example:
setcookie("name","",time()-1);
Similar to using header().

1.4 FAQ Solution:

1) There is an error message when using setcookie(). It may be because there is output or spaces before calling setcookie(). It is also possible that your document was converted from other character sets, and the document may have BOM signature (that is, adding some hidden BOM characters to the file content). The solution is to prevent this situation from happening in your document. You can also handle it by using the ob_start() function.
2) $_COOKIE Affected by magic_quotes_gpc, it may be automatically escaped 3) When using it, it is necessary to test whether the user supports cookies


1.5 Cookie working mechanism:

Some learners are more impulsive and have no time to study the principles, so I put it later.
a) The server sets a cookie in the client by sending an http Set-Cookie header with the response. (Multiple cookies require multiple headers).
b) The client automatically sends an http cookie header to the server, and the server receives and reads it.

HTTP/1.x 200 OK
X- Powered-By: PHP/5.2.1
Set-Cookie: 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
Content-type: text/html

This line implements cookies function, after receiving this line Set-Cookie: TestCookie=something from somewhere; path=/
The browser will create a cookie file on the client's disk and write in it:

TestCookie= something from somewhere;
This line is the result of us using setcookie('TestCookie','something from somewhere','/');. That is, using header('Set-Cookie: TestCookie=something from somewhere; path= /'); result.




2. PHP’s Session

session uses expiration time setting A cookie of 0, and a unique identifier (a long string) called session ID is synchronized to generate some session files on the server side (you can define the session storage type yourself), and associate them with the user machine. Web application The program stores data related to these sessions and allows the data to be passed between pages with the user.

Visitors who visit the website are assigned a unique identifier, the so-called session ID. It is either stored in a client-side cookie or passed via the URL. Session support allows users to register any number of variables and reserve them for each request. When a visitor accesses the website, PHP checks whether a specific session ID was sent in the request, either automatically (if session.auto_start is set to 1) or when the user requests it (explicitly called by session_start() or implicitly by session_register()). If so, the previously saved environment is recreated. 2.1 Transmitting session ID 2.1.1 Transmitting session ID through cookie

Use session_start() to call the session. While generating the session file, the server generates the session ID hash value and the session name with the default value of PHPSESSID, and The variable sent to the client is (default is) PHPSESSID (session name), and the value is a 128-bit hash value. The server will interact with the client through this cookie.
The value of the session variable is passed through the PHP internal series After being converted, it is saved in a text file on the server machine, and interacts with the client's cookie whose variable name is PHPSESSID by default.
That is, the server automatically sends the http header: header('Set-Cookie: session_name()= session_id(); path=/');
That is, setcookie(session_name(),session_id());
When you jump to a new page from this page and call session_start(), PHP will check and give Session data stored on the server side associated with the specified ID. If not found, create a new data set.

2.1.2 Transmit session ID through URL
Only used when the user prohibits the use of cookies This method, because browser cookies are already universal, does not need to be used for security reasons.
xxx, you can also pass the session value through POST.

2.2 Basic usage examples of session
Copy code The 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, the session can be passed directly to page2.php
echo'
page 2';

// If the client disables cookies
echo'
page 2';
/*
Under php5.2.1 by default, SID will only have a value when the cookie is written. If the cookie corresponding to the session
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 need to determine whether our webpage is cached on the client, or set the cache validity time. For example, there is some sensitive content on our webpage and You need to log in to view it. If it is cached locally, you can directly open the local cache and browse to the web page without logging in.

Use session_cache_limiter('private'); you can control the page client cache, which must be in Called before session_start().
For more parameters, see the client cache control at http://blog.chinaunix.net/u/27731/showart.php?id=258087.
To control the client cache time, use session_cache_expire (int); unit (s). It must also be called before session_start().

This is only a method to control the cache when using the session. We can also control the cache of the control page in header().

2.4 Deleting session

requires three steps.
session_destroy(); // The first step: Delete the server-side session file, use setcookie( session_name(),'',time()-3600); // Step 2: Delete the actual session:
$_SESSION= array(); // Step 3: Delete the $_SESSION global variable array?>

2.5 The use of session in PHP large-scale web applications. For sites with a large number of visits, the default session storage method is not suitable. The current best method is to use the database to access the session. At this time, the function bool session_set_save_handler ( callbackopen, callbackclose, callbackread, callbackwrite, callbackdestroy, callbackgc ) provides us with a solution to this problem.
The 6 functions used by this function are as follows:

1. bool open() uses To open the session storage mechanism,

2. bool close() Close the session storage operation.

3. mixde read() Use this function when loading session data from storage 4. bool write () Write all data for the given session ID to storage 5. bool destroy() Destroy the data associated with the specified session ID 6. bool gc() Garbage collection of data in the storage system For an example, see the PHP manual session_set_save_handler () function.
If you use a class to handle it, 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 can change objects without calling static methods, but using static members does not require generating objects, and the performance is better.

2.6 Commonly used session functions:

bool session_start(void); Initialize session
bool session_destroy(void): Delete server-side session associated files. stringsession_id() The id of the current session
stringsession_name() The name of the currently accessed session, which is the cookie name where the client saves the session ID. The default is PHPSESSID.arraysession_get_cookie_params() Details of the session associated with this session.
stringsession_cache_limiter() Controls the client cache of pages using the session ini session_cache_expire() Controls the client cache time bool session_destroy() Delete the file where the session information is saved on the server side void session_set_cookie_params( int lifetime [, stringpath [, stringdomain [, bool secure [, bool httponly]]]] ) sets the details of the session associated with this session bool session_set_save_handler ( callbackopen, callbackclose, callbackread, callbackwrite, callbackdestroy, callbackgc ) defines processing Session function, (not using the default method)
bool session_regenerate_id([bool delete_old_session]) allocates a new session id


2.7 session security issues attackers try to obtain by investing a lot of effort The effective session ID of the existing user. With the session ID, they may have the same capabilities as this user in the system.
Therefore, our main solution is to verify the validity of the 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();
}
?>


2.8 The difference between session passing through cookie and passing through SID:
Default configuration of session in php5.2.1 In this case, when generating the session, the server will generate the predefined super global variable SID while sending the header set-cookie (that is, writing the cookie and throwing the SID are equivalent.), when $_COOKIE[ After 'PHPSESSID'] exists, cookies will no longer be written, and the super global variable SID will no longer be generated. At this time, the SID will be empty.


2.9 Session usage example/**
* Verify the legitimacy 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 the session ID */elseif($_SESSION['user_agent'] != MD5 ($_SERVER['REMOTE_ADDR']
. $_SERVER['HTTP_USER_AGENT'])) {
session_regenerate_id();
}
}

/**
* Destroy session
* Perfectly implemented in three steps, no leaks*
* /functionsessionDestroy() {
session_destroy();
setcookie(session_name(),'',time()-3600);
$_SESSION= array();
}
?> ;

Note:

The reason why the session header information has been sent is the same as the cookie.
In php5, all php session registry configuration options are programmatically configurable , Under normal circumstances, we do not need to modify its configuration. To understand the session registry configuration options of PHP, please refer to the Session processing function in the manual.
When the session saves data, it is through the serialization of the $_SESSION array To store, there are problems with serialization. There may be special character values ​​that need to be encoded with the base64_encode function, and then decoded with base64_decode when reading.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321607.htmlTechArticle1. PHP’s COOKIE cookie is a way to store data on the remote browser and use it to track and identify users. mechanism. PHP sends cookies in the header information of the http protocol, so the setcookie() function must...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template