PHP Session control: Session and Cookie details

Source: Internet
Author: User
Tags php session
This article mainly introduces PHP Session control: Session and Cookie Details. This article describes Session and Cookie related knowledge in PHP in detail and covers a wide range of topics, for more information about PHP session control, see the following:

• Background/concept of session control
• Cookie maintenance and lifecycle (effective time)
• Session maintenance and lifecycle (recovery mechanism)
• Differences and connections between cookies and Sessions
• Question 1: Why does the session become invalid after the cookie is disabled?
• Question 2: The session is lost in ie. a new sessionID is generated every time the page is refreshed (Firefox is normal)
• Simple session and cookie instances

Understand the concept of session control

To understand a concept, we need to understand its background and causes. Here we introduce the WEB environment and its HTTP protocol. Background of session control:
Anyone who has read the relevant information about the HTTP protocol will know that the HTTP protocol is a stateless protocol that allows the WEB server to communicate with the client (browser, http request data is not maintained. http requests are independent and not persistent. That is to say, HTTP does not have a built-in mechanism to maintain the state or relationship between two transactions. When a user requests a page and then requests another page, HTTP cannot tell us whether the two requests come from the same user.

This makes us feel very strange. when we shop on forums or e-commerce websites, as long as we are on this site, no matter how we jump, we can go from one page to another, websites always remember who I am, for example, telling you what you bought. How can this be done? as you may have guessed, HTTP session control is used. Track a variable on the website and associate multiple request items by tracking the variable. different content and pages are displayed based on the authorization and user identity.

PHP Session control:

PHP session is driven by a unique session ID, which is an encrypted random number generated by PHP and stored on the client during the session lifecycle. We know that the client (that is, the browser) only saves data in cookies, so the session ID of PHP is generally stored in the cookie of the user's machine. After understanding the cookie, we know that the browser can disable the cookie, so that the session will become invalid. So there is another PHP session control mode, that is, passing session IDs in URLs. If we pay attention to it when browsing the website, some URLs have strings that look like random numbers, it is very likely that they are URL-based session control.

Here, some people may have doubts. the client only saves a session ID, so the session variables saved in session control, such as the list of items you bought during shopping, where are they stored? Obviously, session variables are used on the server, so these session variables must be stored on the server. By default, session variables are stored in common files on the server (you can also configure and use the database to save them, you can Google it). Session IDs act as a key, find the session variable corresponding to the session ID in the file where the server saves the session, such as the list of purchased items.

The entire session control process may look like this. when a user logs on to a website or browses a page for the first time, this site generates a PHP session ID and sends it to the client (browser) through cookies ). When a user clicks another page of the site, the browser starts to connect to the URL. Before connection, the browser will first search for the locally saved cookie. if there is any cookie related to the URL being connected in the cookie, it will be submitted to the server. A cookie (saved session ID) related to the URL of the website has been generated during login or the first connection, so when the user connects to the site again, the site can identify the user through this session ID, and retrieve the session variables related to this session ID from the server session file to maintain the continuity between transactions.

Next, we will understand two important concepts: cookie and session.

Cookie maintenance and lifecycle

Cookie is created on the server side and written back to the client browser. the browser receives the cookie writing instruction in the response header in the local temporary folder.

A cookie file is created, where your cookie content is saved. the cookie content is stored as a key-value pair, and both keys and values can only be strings. For example:
File: Cookie: administrator @ localhost/
Content Format: voteID100101localhost/15361167667230343893360385046430343691 *

Cookie Creation:

The code is as follows:


The setcookie () function sets the cookie. the Function prototype is as follows:
Setcookie (name, value, expire, path, domain );

Note: the cookie header must be sent before other headers are sent. Otherwise, it will be invalid (this is a cookie restriction, not a PHP restriction ). When sending a cookie, the cookie value is automatically URL encoded and automatically decoded when Retrieved. to prevent URL encoding, use setrawcookie () instead ).

Cookie maintenance:

Coke has four identifiers: cookie name, domain, path, and secure. To change the value of this cookie in the future, you need to send another Set-cookie message header with the same Cookie name, domain, path.

To overwrite the original cookie value. However, if only one of these options is changed, a completely different cookie is created, for example, the name value is changed.

Cookie expiration time:

You can set the expiration time. if you do not set the expiration time, it is the session level, that is, closing the browser will disappear. When a cookie is created, it contains an expiration date, which is associated with a cookie identified by name-domain-path-secure. To change the expiration date of a cookie, you must specify the same combination. When changing the value of a cookie, you do not need to set the expiration date every time because it is not part of the cookie identity information. For example:

The code is as follows:


Setcookie (vote, $ id + 1, time () + 3600*24 );
Setcookie (vote, $ id );

The expiration date on the cookie does not change because the cookie identifier is the same. In fact, only you manually change the cookie expiration date, otherwise the Expiration Date will not change. This means that in the same session, a session cookie can be converted into a persistent cookie (one that can exist in multiple sessions), and vice versa. To change a persistent cookie to a session cookie, you must delete this persistent cookie, this only requires you to set its expiration date to a session cookie with the same name after a certain time in the past.

Remember that the expiration date is verified based on the system time on the computer running the browser. There is no way to verify whether the system time is synchronized with the server time, so when the server time and the browser's system time are different, this setting will cause errors.

Automatic cookie deletion:

The cookie is automatically deleted by the browser. there are usually the following reasons:
Session Coke (Session cookie) will be deleted at the end of the Session (closed by the browser)
Persistent cookie will be deleted when it reaches the expiration date, for example:

The code is as follows:


Setcookie ("vote", "", time ()-3600 );


If the cookie in the browser is restricted, the cookies will be deleted to create a space for creating new cookies.

Session maintenance and lifecycle

Session is a server-side storage space maintained by the application server. when you connect to the server, the server creates a unique sessionID, this sessionID is used as the identifier to access the Session bucket of the server. during the Session, the unique sessionID assigned to the client is used to identify the current user and distinguish it from other users. The SessionID is used to receive each access request, so as to identify the current user, track and maintain the user's specific information, and session variables, and store numbers or text in the session. for example, session_name. the information is stored on the server. Of course, sessionID can also be saved to the database as session information for session persistence. In this way, the user's login times, online or not, online time, and so on can be tracked to maintain the relationship between HTTP stateless events. Session content storage is a list of key-value pairs, and keys are strings. session storage is more convenient and values can be objects.

During a session, the session is saved on the client and server respectively. the client can be the sessionID saved in cookie mode (the default storage method) or transmitted in the url string format. The server is generally saved in the specified session directory as text. On the server side, we can use session. use_cookies to control which storage method the client uses. If it is defined as the cookie storage method, we can control the validity period of the cookie stored on the client through session. cookie_lifetime (0 by default, which is cleared when the browser is closed. If the client saves the sessionID as a cookie, use the "temporary" cookie to save it (the cookie name is PHPSESSID. you can learn the details through Firebug, you can use php. ini session. the user submits the SessionID to the server to access session data when submitting the page. This process requires no developer intervention.

Session creation:

The code is as follows:


Session_start () // start a session and return an existing session


Function: Initializes the Session and marks the beginning of the session lifecycle. To use the session, you must initialize a session environment, which is similar to calling the constructor in the OOP concept to create an object instance. The session initialization operation declares a global array $ _ SESSION, which maps the session data stored in the memory. If the session file already exists and the session data is saved, session_start () reads the session data and fills in $ _ SESSION to start a new session lifecycle.

Note: This function has no parameter and returns true. If cookie-based sessin is used, no output is available before session_satrt (), including blank output.
If. session in ini. if auto_start = 1 is enabled, run session_start () on each page. you do not need to set it manually. this option is disabled by default. after it is enabled, the object cannot be put into the session.

Session ID:

The unique identifier of a user session. it is a random string that is unique and random. It is mainly used to differentiate session data of other users. When a user accesses the web page for the first time, the php session initialization function call will be assigned a unique ID to the current user, also known as session_id.

Obtain session_id ():

The code is as follows:


Echo $ _ COOKIE ['phpsessid'].'
';
Echo $ _ COOKIE [session_name ()].'
';
Echo session_id ().'
';

Session Data:

The user status information that needs to be saved through the session is called the user session data, also known as the session data. Generally, $ _ session data is generated during the current SESSION lifecycle. Once session_start () is called to initialize the session, a session lifecycle starts. That is to say, you can use the relevant function to operate $ _ SESSION to manage session data. The data generated during the session lifecycle is not written to the session file in real time, but is stored in the memory through the $ _ SESSION variable. $ _ SESSION is a global variable and its type is Array. it maps session data of the session lifecycle and is stored in the memory. During session initialization, read data from the session file and fill in the variable. At the end of the session (lifecycle), write $ _ SESSION data back to the session file.

Register a session variable:

After PHP4.1, SESSION variables are stored in the Super Global Array $ _ SESSION. To create a session variable, you only need to set an element in the array, such:

The code is as follows:


$ _ SESSION ['domain '] = blog.bitsCN.com;
$ _ SESSION ['poll '] = $ _ SESSION [poll] + 1;


Use a session variable:

The code is as follows:


Echo $ _ SESSION ['blogdomain ']; // Print out blog.bitsCN.com. before using the SESSION, you must use the session_start () function to start a SESSION.

Cancel Session variable/destroy Session:

The code is as follows:


Unset ($ _ SESSION); // destroy a single SESSION variable
For example, unset ($ _ SESSION ['blogdomain ']);
# The unset ($ _ SESSION) function will destroy the global variable $ _ SESSION, and there is no feasible way to restore it. You can no longer register the $ _ SESSION variable. Therefore, this function cannot be used.

Session_unset (); // multiple releases. Release all the variables logged in to the session file.
# In the session lifecycle, cancel all session data from the current session and make $ _ SESSION an empty array. It differs from unset ($ _ SESSION) in that unset directly deletes the $ _ SESSION variable to release memory resources. Another difference is that session_unset () the $ _ session array can be operated only during the SESSION lifecycle, while unset () can operate the $ _ SESSION array throughout the page lifecycle. Session_unset () does not perform any IO operations, but only affects the $ _ SESSION array.

$ _ SESSION = array (); // multiple releases, releasing all the variables logged on to the $ _ SESSION parameter

Session_destroy ();
# After a session is used, you should first cancel all the variables, then call this function to end the current session, clear all resources in the session, and delete the session files on the server. this function does not unset (release) global variables related to the current session, nor delete the client session cookie.
# If session_start () is used to initialize a session, it logs out a session. The session lifecycle is over. After the session lifecycle is completed, the $ _ SESSION array and $ _ SESSION ['domain '] cannot be operated, while the $ _ SESSION array can still be unset () and other function operations. In this case, the session is undefined, and the $ _ SESSION is still a global variable. they are out of the ing relationship.
You can use session_destroy () to cancel a session. in addition to closing the session lifecycle, it also deletes the sesion file, but does not affect the current $ _ SESSION variable. That is, it will generate an IO operation.

Note:

1. the default session of php is based on cookies. to delete a cookie, you must use the setcookie () function.
2. differences between session_unset () and unset () functions:

In the session lifecycle, session_unset () cancels all session data from the current session, making $ _ SESSION an empty array. It differs from unset ($ _ SESSION) in that unset directly deletes the $ _ SESSION variable to release memory resources. Another difference is that session_unset () the $ _ session array can be operated only during the SESSION lifecycle, while unset () can operate the $ _ SESSION array throughout the page lifecycle. Session_unset () does not perform any IO operations, but only affects the $ _ SESSION array.

Session life cycle: the mechanism of session expiration time and recovery
We start session initialization until the session is canceled, which is called the session lifecycle.
By default, php saves the session in the directory set by session. save_path in the php. ini configuration. the file name is as follows: sess_ves0d7uvdsab9k6sig73mnn592. Each file corresponds to a session ). The session file format is roughly as follows:

The code is as follows:


Poll_200 | I: 1; poll_100 | I: 3; // # variable name | type: Length: value

Set the SESSION lifecycle:

The php session is based on cookies. therefore, to set the session lifecycle, you must first set the cookie expiration time. When a client (such as a browser) logs on to a website, it checks whether the client has a COOKIE and uses the session id in the COOKIE to find the files on the server.

The code is as follows:


Session_start ();
$ LifeTime = 24*3600; // save for one day
Setcookie (session_name (), session_id (), time () + $ lifeTime ,"/");

In fact, PHP5 Session also provides a function session_set_cookie_params (); to set the lifetime of PHP5 Session. this function must be called before the session_start () function is called:

The code is as follows:


$ LifeTime = 24*3600; // save for one day
Session_set_cookie_params ($ lifeTime );
Session_start ();

On the server side, how does php determine whether the session file has expired?

The code is as follows:


Session. gc_maxlifetime = 1440 (initial value)
# Set the session survival time in seconds. After each GC is started, the unix time for the last access to the session file is obtained through stat. if the current time minus the last access time of the file is greater than session. gc_maxlifetime, the file is deleted.

If the "last modification time" has exceeded the "session. gc_maxlifetime (the default value is 1440) seconds. that is to say, the file has not been modified within the time set here, and the session file is considered to have expired, since the session in php5 adopts a passive recycle mechanism, expired session files will not disappear, but will be processed by triggering "recycle". In this case, when the next session is recycled, if this file has not been changed, the session file will be deleted (The session will expire ).

When does session recycling happen?

By default, every php request will have a 1% probability of recovery, so it may be simply understood as "every 100 php requests may have a recovery probability ". This probability is controlled by the following parameters:

The code is as follows:


Session. gc_probability = 1 (initial value)
Session. gc_pisor = 100 (initial value)
# The probability of GC activation is determined by these two functions. the default value is 1/1000. That is to say, one of every one thousand user requests will start GC to recycle the session. The GC process should not be started too frequently. Websites with too frequent access and high concurrency can reduce the startup frequency of php gc. Php gc recycle session will reduce the execution efficiency of php.

These two methods are used together to start the management probability of the Gabadge Collection (gc) process. when the session is first activated (session_start ()). After the Gabadge Collection is started, it traces the session information file. The startup probability is session. gc_probability/session. gc_pisor. That is to say, not every session information file is processed as garbage by the system. If you close the browser directly, the session information file is often left on the server. if you change the probability to 100%, although the Gabadge Collection is fully started, this adds load to the server, the significance of GC itself is lost.

Note:

1. assume that the session is in this situation. gc_maxlifetime = 1440. if the last modification time of a session file is 1440 seconds ago, the session is still valid until the next recovery (1/100 probability) occurs;

2. if your session is saved elsewhere in session. save_path, the session recycle mechanism may not automatically process expired session files. In this case, you need to manually (or crontab) delete expired sessions: cd/path/to/sessions; find-cmin + 24 | xargs rm;

3. Note that when the number of session files on the server side is not effectively recycled and gradually increases to GB or a higher level, your site may become slower and slower when accessing the session, most often seen in the site login and logout will be affected;

4. when writing logs, weekly reports, monthly reports, and so on, there may be "invalid operations, please log in and try again" and other messages. The reason is self-evident, it may be that the session is invalid. gc clears the session files that have timed out.

Some special cases:

Because the recycle mechanism checks the "last modification time" of the file, if a session is active but the session content has not changed, the corresponding session file has not changed, the recycle mechanism will delete a session that is not active for a long time. This is something we don't want to see. you can solve this problem by adding the following simple code:

The code is as follows:


<? Php
If (! Isset ($ _ SESSION ['last _ access']) | (time ()-$ _ SESSION ['last _ access'])> 120)
$ _ SESSION ['last _ access'] = time ();
?> // The Code attempts to modify the session every 120 seconds.

Understanding the differences and connections between cookies and Sessions

Similarities: both of them can solve the problem of stateless HTTP, so that the same client can save, set information, and establish a connection between request items in multiple requests to visit the website.

Difference: simply put, cookie information is stored on the client, and session information is stored on the server.

Session uses key-value pairs, that is, the ID stores the client, and the value is placed on the server. the user ID is used to find the corresponding value on the server. in this way, the value is placed on the server, there is a time limit. when the time is reached, the server will be automatically recycled/released.

Cookies can be stored in a browser variable. one method is to save the value in the browser variable. when the browser is closed, the cookie ends. The other method is to save the cookie to the hard disk, as long as the time does not expire, it can be used again next time.

Contact: when the client uses the SessionID saved in Cookie-based mode, SessionID is generally stored in cookie.

Note: cookies are shared between browsers with the same kernel. different kernels are not shared, for example, Firefox and IE (the storage locations are different, but they are not shared ). Different kernel browsers cannot share cookies and may also generate different sessionids.

Question 1: Why does the session become invalid after the cookie is disabled?

First, note that session does not necessarily depend on cookies, but the session id of the default php client is saved as a cookie.

At this point, I think you should also understand that the default session client in php is stored based on cookies. Therefore, once the cookie is disabled on the client, the cross-page session will become invalid, I don't know if this description is appropriate. In general, stateless things must be changed to stateful, and can only be compared on both sides. if SessionID is saved in cookie mode, the comparison conditions on the client side are stored in the cookie. Therefore, when the client disables the cookie, the session will also become invalid. The session client ID of php generally has two storage methods: cookie and url. If the session ID is saved in the cookie, you can see that there is a PHPSESID variable in the browser's cookie (which can be viewed in firefox ). If the URL is passed (we recommend that you use a hidden form for transfer), you can see the following figure: index. php? PHPSESID = ves0d7uvdsab9k6sig73mnn592 URL. For example:

The code is as follows:


Demo1.php
<? Php
Session_start ();
$ _ SESSION ['blog '] = 'http: // blog.bitsCN.com ';
Echo "test2 ";
?>

Demo2.php
<? Php
Session_start ();
Echo 'session value is '. $ _ session ['blog'];
?>

Run the above code, in the client cookie normal circumstances, I can print out $ _ SESSION ['blog '] in demo2.php value: http://blog.bitsCN.com. However, if you manually disable the client cookie and run the instance again, the result may not be returned. Because the default client sessionid is saved across pages, the sessionid of the previous page cannot be read. when session_start (); is executed, a session file is generated, generate the corresponding session id. this session id cannot be used to retrieve the variables in the first session file mentioned above, because this session id is not the "key" to open it ". If the code session_id ($ sessionid) is added before session_start (); no new session file is generated and the session file corresponding to this id is directly read. Simply put, the session id is obtained on the previous page, and then you can find a way to pass the session id to the next page, on the session_start () of the next page. before the code, add the code session_id (the passed sessionid). For example:

The code is as follows:


Demo. php
<? Php
$ Sid = $ _ GET ['Sid '];
If (! Empty ($ sid )){
Session_id ($ sid );
Session_start ();
} Else {
Session_start ();
$ Sid = session_id ();
}
?>

Demo2.php
<? Php
$ Sid = $ _ GET ['Sid '];
If (! Empty ($ sid )){
Session_id ($ sid );
Session_start ();
} Else {
Session_start ();
$ Sid = session_id ();
}
$ Id = $ _ POST ['id'];
$ Key = 'poll _ '. $ id;
If ($ id! = ''){
Echo $ key = 'poll '. $ id;
If (! Empty ($ _ SESSION [$ key]) {
$ _ SESSION [$ key] =_ _ SESSION [$ key] + 1;
} Else {
$ _ SESSION [$ key] = 1;
Setcookie ($ key, $ id + 1, time () + 3600*24 );
}
Echo 'script alert ("success"); javascript: location. href = "demo. php? Sid = '. $ sid.' "; script ';
} Else {
Echo 'script alert ("failed! ID Null "); javascript: history. back (-1); script ';
}
?>

In addition, we can also store the client PHPSESID in a file, such:

The code is as follows:


Demo. php
Session_start ();
$ _ SESSION ['blogdomain '] = 'http: // blog.bitsCN.com ';
$ Sid = session_id ();
$ Fp = fopen ("D: \ tmp \ websid.txt", "w + ");
Fwrite ($ fp, $ sid );
Fclose ($ fp );
Echo 'demo2 ';

Demo2.php
$ Fp = fopen ("D: \ tmp \ websid.txt", "r ");
$ Sid = fread ($ fp, 1024 );
Fclose ($ fp );
Session_id ($ sid );
Session_start ();
Print_r ($ _ SESSION );

When the client disables the cookie, you can change the session's dependency on the client cookie in the following ways to enable the session to discard the client cookie:

1. set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option when compiling, so that PHP can automatically pass the session id across pages. When session. use_trans_sid is valid, ession. use_only_cookies must be set to invalid 0.

2. manually pass session IDs through URL values and hidden forms.

3. save session_id in the form of files and databases, and manually call it during the cross-page process.

PHP also provides a function:

The code is as follows:


Output_add_rewrite_var (string $ name, string $ value) # variable name variable value

Note: This function adds name/value pairs to the URL rewriting mechanism. This type of name-value pair will be added to the URL (in the form of a GET parameter) and form (in the form of an input hidden field). when a transparent URL is rewritten, session will be used. when use_trans_sid is enabled, it can also be added to the session ID. Note that absolute URLs (http://bitsCN.com/..) cannot be overwritten. The behavior of this function is controlled by the url_rewriter.tags php. ini parameter.

The code is as follows:


<?
Session_start ();
Output_add_rewrite_var ('phpsessid ', session_id ());
Echo 'demo ';
?>

In this way, sessionID will be followed by the URL and the hidden value of sessionID will appear in from.

Change the session client ID storage method:

Session. use_cookies // specifies the method used by the client to save the SessionID. when it is set to "1", it indicates that the session cookie is started (the initial value is 1)
You can use the function we mentioned above to query the current session id: echo $ _ COOKIE ["PHPSESSID"];
However, if the client browser does not support cookies, even if the value of session. use_cookies is equal to "1", the above query will only get null.

Two configuration parameters related to this option in php. ini:

The code is as follows:


Session. use_cookies = 1 // whether to use cookies (default value: 1)
Session. use_only_cookies = 1 // when the value is 1, only cookies are used. when the value is 0, cookies and other methods can be used. if the client cookie is available, the session still uses cookies by default (the default value is 1)

Note: If your browser supports cookies, we strongly recommend "session. use_only_cookies = 1 "when session. when use_only_cookies are valid, the session id is considered invalid even if you want to pass the session id through the URL. this reduces the possibility of being attacked by sessionid. The above two configurations are set on the php code page:

The code is as follows:


Ini_set ('session. use_cookies ', '1 ');
Ini_set ('session. use_only_cookies ', '1 ');

Session loss in IE. a new sessionID will be generated every time the page is refreshed (Firefox is normal)

If this problem occurs on your server or site, configure the session. cookie_path website domain correctly. if the configuration is incorrect, the following common faults may occur:

(1) each PHPSESSID of the client will generate an independent session record one to one on the server, therefore, the server session file redundancy will increase (when the GC recovery mechanism is abnormal and the site traffic is large)

(2) websites that use session to record relevant information may encounter access problems in browsers other than Firefox (Chrome not tested). For example, shopping cart cannot record purchase items or site logon failures.

The code is as follows:


Session. cookie_path indicates the website domain in which the session takes effect;
Session. save_path refers to the path for storing temporary session files.
Example: session. cookie_path = // valid cookie path

Supplement: if a new sessionID is generated when all browsers are refreshed, check whether the cookie is disabled on the client.

Simple session instance

Use session to prevent repeated form submission:

The code is as follows:


<? Php
Session_start ();
$ _ SESSION ["num"] = 0;
If (isset ($ _ POST ["action"] & $ _ POST ["action"] = "post ")){
If ($ _ SESSION ["num"] = 0 ){
Echo "submitted successfully! ";
$ _ SESSION ["num"] = 1;
} Else {
Echo "do not submit again! ";
}
}
?>

Session-based logon verification instance code:

The code is as follows:


<? Php
Session_start (); // start the session, which must be placed in the first sentence; otherwise, an error occurs.
If ($ _ GET ['out']) {
Unset ($ _ SESSION ['id']);
Unset ($ _ SESSION ['pass']);
}
If ($ _ POST ['name'] & $ _ POST ['password']) {
// Set the session
$ _ SESSION ['id'] = $ _ POST ['name'];
$ _ SESSION ['pass'] = $ _ POST ['password'];
}
If ($ _ SESSION ['id'] & $ _ SESSION ['pass']) {
Echo "logon successful!
User id: ". $ _ SESSION ['id']."
User password: ". $ _ SESSION ['pass'];
Echo"
";
Echo "deregistering a session ";
}

?>

Use the cookie-based logon verification instance code:

The code is as follows:


If ($ _ GET ['out']) {// used to cancel cookies
Setcookie ('id ',"");
Setcookie ('pass ',"");
Echo "script" location. href = 'login. php 'script '; // because cookies do not take effect immediately, they only take effect when you refresh again. Therefore, after cancellation, the page is automatically refreshed.
}
If ($ _ POST ['name'] & $ _ POST ['password']) // if the variable username and password exist, set cookies below
{// Used to set cookies
Setcookie ('id', $ _ POST ['name'], time () + 3600 );
Setcookie ('pass', $ _ POST ['password'], time () + 3600 );
Echo "script location. href = 'login. php' script"; // enables cookies to take effect immediately
}
If ($ _ COOKIE ['id'] & $ _ COOKIE ['pass']) {// cookies are displayed after they are successfully set.
Echo "logon successful!
Username: ". $ _ COOKIE ['id']."
Password: ". $ _ COOKIE ['pass'];
Echo"
";
Echo "deregistering cookies ";
}
?>


Use the random session code to verify the voting validity:

The code is as follows:


List. php option page
Session_start ();
$ TokenKey = md5 (rand (1,100 ));
$ _ SESSION ['tokenkey'] = $ tokenKey;
Note: the random code $ tokenKey is also input when the value is passed.

Vote. php voting action execution page
$ TokenKey = $ _ SESSION ['tokenkey'];
If ($ _ POST ['tokenkey']! = $ TokenKey) {// judge whether the random code is the same as the previous page
Echo "script" alert ('Please vote again! '); Location. href = 'list. php'; script "; // invalid random code
Exit;
} Else {
Execute the voting operation;
Clear random codes stored in session
}

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.