The PHP Setcookie () function sends an HTTP cookie to the client. A cookie is a variable that is sent by the server to the browser. Cookies are usually small text files that the server embeds into the user's computer. This cookie is sent whenever the computer requests a page through the 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 it returns false.
1 Setcookie (name, value, expire, path, domain, secure)
name required. Specify the name of the cookie.
value required. Specify the value of the cookie.
expire optional. Specify the expiration date of the cookie.
path Optional. Specify the server path for the cookie.
Domain optional. Specify the domain name of the cookie.
Secure Optional. Specify whether to transmit cookies through a secure HTTPS connection.
You can access the value of a COOKIE named "User" by $HTTP _cookie_vars["user" or $_cookie["user". When a cookie is sent, the value of the cookie is automatically URL-coded. The URL is decoded when it is received. If you do not need this, you can use Setrawcookie () instead.
example, PHP settings and get cookies
The code is as follows |
Copy Code |
Setcookie (' MyCookie ', ' value '); function prototypes: int Setcookie (string name,string value,int expire,string path,string Secure) Echo ($mycookie); Echo ($HTTP _cookie_vars[' MyCookie ']); Echo ($_cookie[' MyCookie ')); |
Delete Cookies
(1) Invoke the Setcookie () with the name parameter only;
(2) to make the time of expiration () or time-1;
The code is as follows |
Copy Code |
<?php Setcookie (' name ');?> Setcookie (' MyCookie '); or Setcookie (' MyCookie ', '); or Setcookie ("MyCookie", false); Setcookie (' MyCookie ', ', ', Time ()-3600); Echo ($HTTP _cookie_vars[' MyCookie ']); Print_r ($_cookie); |
Suggested deletion method:
The code is as follows |
Copy Code |
Setcookie (' MyCookie ', ', ', Time ()-3600); |
PHP provides a very useful function mktime ().
You just send it to mktime in order () The hours, minutes, seconds, months, dates, and years that you want to represent
Mktime () returns the total number of seconds for the date from January 1, 1970.
Therefore, if you need to simulate Y2K problems:
The code is as follows |
Copy Code |
$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 cookie expiration time
The code is as follows |
Copy Code |
$expire = time () + 86400; Set a 24-hour validity period Setcookie ("Var_name", "Var_value", $expire); Set a cookie with a name of Var_name and set the expiration date Setcookie ("Var_name_expire", $expire, $expire); Set the expiration time into a cookie so you can know the expiration time of the Var_name |
Note:
When a cookie is sent, the value of the cookie is automatically URL-coded. The URL is decoded when it is received.
If you do not need this, you can use Setrawcookie () instead.
example, cookies to save user login information
1. Database Connection Configuration page: connectvars.php
The code is as follows |
Copy Code |
<?php 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
The code is as follows |
Copy Code |
<?php Insert information about the connection database Require_once ' connectvars.php '; $error _msg = ""; Determine if the user has set cookies, and if $_cookie[' user_id ' is not set, execute the following code if (!isset ($_cookie[' user_id ')) { if (Isset ($_post[' submit ')) {//Determine whether the user submits the login form, and if so, 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 ') ";
Query with user name and password
$data = Mysqli_query ($dbc, $query);
If the record is exactly one, set the cookie and page redirection
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 not correct, set the error message
$error _msg = ' Sorry, must enter a valid username and password to log in. '
}
}else{
$error _msg = ' Sorry, must enter a valid username and password to log in. '
}
}
}else{//If the user is logged in, jump directly to the already logged on page
$home _url = ' loged.php ';
Header (' Location: '. $home _url);
}
?>
<html>
<head>
<title>mismatch-log in</title>
<link rel= "stylesheet" type= "Text/css" href= "Style.css"/>
</head>
<body>
<h3>msimatch-log in</h3>
<!--by $_cookie[' user_id '], if the user is not logged in, then display the login form, let the user enter a username and password-->
<?php
if (Empty ($_cookie[' user_id ')) {
Echo ' <p class= ' Error > '. $error _msg. ' </p> ';
?>
<!--$_server[' Php_self '] invokes its own PHP file when submitting a form on behalf of a user-->
<form method = "Post" action= "<?php echo $_server[' php_self '];? > ">
<fieldset style= "width:250px;" >
<legend>log in</legend> <label for= "username" >Username:</label>
<!--If the user has already lost the user name, echo the user name-->
<input type= "text" id= "username" name= "username"
Value= "<?php if (!empty ($user _username)) echo $user _username;?>"/>
<br/>
<label for= "Password" >Password:</label>
<input type= "password" id= "password" name= "password"/>
</fieldset>
<br/>
<input type= "Submit" value= "Log in" name= "Submit"/>
</form>
<?php
}
?>
</body>
</html> |
3, login page: loged.php
The code is as follows |
Copy Code |
<?php Logged in page showing logon username if (isset ($_cookie[' username ')) { Echo ' You are logged as '. $_cookie[' username '. ' <br/> '; Click "Log Out", then go to the logout.php page to log off the cookie Echo ' <a href= "logout.php" > Log out ('. $_cookie[' username '). " </a> '; } /** in the logged on page, you can take advantage of the user's cookies such as $_cookie[' username ', * $_cookie[' user_id '] to query the database, you can do a lot of things. ?> |
4. Logout Cookie page: logout.php (redirect to lonin.php after logoff)
The code is as follows |
Copy Code |
<?php /**cookies Logout Page * * if (Isset ($_cookie[' user_id ')) { Set the expiration time of each cookie to a time in the past so that they are 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); ?> |
In conclusion, we must pay attention to three points
1: Considerations When setting cookies
Cookies are set up in the same page, in fact, in sequential order. If you want to delete a cookie and then write a cookie, you must write the statement first, and then write the deletion statement. Otherwise, there will be an error.
2:setcookie examples
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.111cn.net", 1);
Some characteristics 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. The specified path forces the server to use the path of the setting.
Cookies in one directory page are not visible on the page of another directory.