PHP cookie How to learn notes share _php Tutorial

Source: Internet
Author: User
Tags http cookie setcookie
The PHP Setcookie () function sends an HTTP cookie to the client. A cookie is a variable that is sent to the browser by the server. A cookie is usually a small text file that the server embeds into a user's computer. This cookie is sent whenever the computer requests a page through a browser. The name of the cookie is specified as a variable of the same name. For example, if the cookie being sent is named "name", a variable named $user is automatically created, containing the value of the cookie.

The cookie must be assigned before any other output is sent. If successful, the function returns True, otherwise false is returned.

1 Setcookie (name, value, expire, path, domain, secure)
Datastore required. Specifies the name of the cookie.
value required. Specifies the value of the cookie.
expire is optional. Specify the validity period of the cookie.
path is optional. Specifies the server path of the cookie.
domain is optional. Specifies the domain name of the cookie.
secure is optional. Specifies whether to transfer cookies through a secure HTTPS connection.
You can access the value of the COOKIE named "User" by $HTTP _cookie_vars["user"] or $_cookie["user". When a cookie is sent, the value of the cookie is automatically URL-encoded. The URL is decoded when it is received. If you don't need this, you can use Setrawcookie () instead.

example, PHP settings and get cookie

Copy the Code code as follows:
Setcookie (' MyCookie ', ' value ');

function prototypes: int Setcookie (string name,string value,int expire,string path,string domain,int Secure)
Echo ($mycookie);
Echo ($HTTP _cookie_vars[' MyCookie ');
Echo ($_cookie[' MyCookie ');

Delete Cookies

(1) Call Setcookie () with the name parameter only;
(2) to make the expiry time () or time-1;

Copy the Code code as follows:

Setcookie (' MyCookie '), or Setcookie (' MyCookie ', '), or Setcookie ("MyCookie", false);
Setcookie (' MyCookie ', ', Time ()-3600);
Echo ($HTTP _cookie_vars[' MyCookie ');
Print_r ($_cookie);

Suggested removal method:

Copy the Code code as follows:
Setcookie (' MyCookie ', ', Time ()-3600);

PHP provides a very useful function mktime ().
You simply send the order to Mktime () the hour, minute, number of seconds, month, date, and year that you wish to represent,
Mktime () returns the total number of seconds that date has been since January 1, 1970.
Therefore, if you need to simulate Y2K problems:

Copy the Code code as follows:
$y 2k = mktime (0,0,0,1,1,2000);
Setcookie (' name ', ' value ', $y 2k);
Setcookie (' name ', ' value ', time+3600);
Setcookie (' name ', ' value ', $y 2k, ' ~/myhome ', '. domain.com ');

Ways to get the cookie expiration time

Copy the Code code as follows:
$expire = time () + 86400; Set the 24-hour validity period
Setcookie ("Var_name", "Var_value", $expire); Set a cookie named Var_name, and establish a validity period
Setcookie ("Var_name_expire", $expire, $expire); Then set the expiration time to a cookie so that you can know the expiration time of the Var_name

Note:

When a cookie is sent, the value of the cookie is automatically URL-encoded. The URL is decoded when it is received.
If you don't need this, you can use Setrawcookie () instead.


example, a cookie to save a user's login information


1. Database Connection Configuration page: connectvars.php

Copy the Code code as follows:
Location of the database
Define (' db_host ', ' localhost ');
User name
Define (' Db_user ', ' root ');
Password
Define (' Db_password ', ' 19900101 ');
Database name
Define (' db_name ', ' test ');
?>

2. Login page: login.php

Copy the Code code as follows:
Inserting information about a connected database
Require_once ' connectvars.php ';

$error _msg = "";
Determine if the user has set a COOKIE, and if $_cookie[' user_id ' is not set, execute the following code
if (!isset ($_cookie[' user_id ')) {
if (Isset ($_post[' submit ')) {//Determine if the user submits the login form, if yes, execute the following code
$DBC = Mysqli_connect (db_host,db_user,db_password,db_name);
$user _username = mysqli_real_escape_string ($dbc, trim ($_post[' username '));
$user _password = mysqli_real_escape_string ($dbc, trim ($_post[' password '));

if (!empty ($user _username) &&!empty ($user _password)) {
The SHA () function in MySQL is used for one-way encryption of strings
$query = "Select user_id, username from mismatch_user WHERE username = ' $user _username ' and '." Password = SHA (' $user _password ') ";
Querying with a user name and password
$data = Mysqli_query ($dbc, $query);
If the record is exactly one, set the cookie and redirect the page
if (Mysqli_num_rows ($data) ==1) {
$row = Mysqli_fetch_array ($data);
Setcookie (' user_id ', $row [' user_id ']);
Setcookie (' username ', $row [' username ']);
$home _url = ' loged.php ';
Header (' Location: '. $home _url);
}else{//If the record is incorrect, set the error message
$error _msg = ' Sorry, you must enter a valid username and password to log in. ';
}
}else{
$error _msg = ' Sorry, you must enter a valid username and password to log in. ';
}
}
}else{//If the user is already logged in, jump directly to the already logged in page
$home _url = ' loged.php ';
Header (' Location: '. $home _url);
}
?>


<title>Mismatch-log in</title>



Msimatch-log in



if (Empty ($_cookie[' user_id ')) {
Echo '

'. $error _msg. '

';
?>


}
?>


3. Login page: loged.php

Copy the Code code as follows:
Logged in page, display login user name
if (isset ($_cookie[' username ')) {
Echo ' You are logged as '. $_cookie[' username '. '
';
Click "Log Out" to go to the logout.php page to log off the cookie
Echo ' Log out ('. $_cookie[' username ') ';
}
/** on the login page, you can take advantage of the user's COOKIE such as $_cookie[' username '),
* $_cookie[' user_id '] query the database, you can do a lot of things * *
?>

4. Logout Cookie page: logout.php (redirected to lonin.php after logout)

Copy the Code code as follows:
/**cookies Logout Page */
if (Isset ($_cookie[' user_id ')) {
Set the expiry time of each cookie to a time in the past, so that it is deleted by the system, in seconds
Setcookie (' user_id ', ', Time ()-3600);
Setcookie (' username ', ', Time ()-3600);
}
Location header redirects the browser to another page
$home _url = ' login.php ';
Header (' Location: '. $home _url);
?>

Finally summing up three points, we must pay attention to

1: Precautions When setting cookies

Setting cookies on the same page is actually done in a backward-forward order. If you want to delete a cookie before writing a cookie, you must write the statement and then write the DELETE statement. Otherwise, an error occurs.

2:setcookie Example

Simple: Setcookie ("MyCookie", "Value_of_mycookie");
With Expiration: Setcookie ("Withexpire", "Expire_in_1_hour", Time () +3600);
Everything: Setcookie ("Fullcookie", "Full_cookie_value", time+3600, "/forum", "Www.jb51.net", 1);

Some features of 3:cookie

Cookies are path-oriented. When the default Path property is used, the Web server page automatically passes the current path to the browser. Specifying a path forces the server to use the path of the setting.
Cookies placed on one directory page are not visible on the page of another directory.

http://www.bkjia.com/PHPjc/825079.html www.bkjia.com true http://www.bkjia.com/PHPjc/825079.html techarticle the PHP Setcookie () function sends an HTTP cookie to the client. A cookie is a variable that is sent to the browser by the server. Cookies are usually small text files that the server embeds into the user's computer ...

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