PHP Cookie Method Learn note sharing

Source: Internet
Author: User
Tags http cookie php file setcookie trim

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) &amp;&amp;!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);


}


?&gt;


&lt;html&gt;


&lt;head&gt;


&lt;title&gt;mismatch-log in&lt;/title&gt;


&lt;link rel= "stylesheet" type= "Text/css" href= "Style.css"/&gt;


&lt;/head&gt;


&lt;body&gt;


&lt;h3&gt;msimatch-log in&lt;/h3&gt;


&lt;!--by $_cookie[' user_id '], if the user is not logged in, then display the login form, let the user enter a username and password--&gt;


&lt;?php


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


Echo ' &lt;p class= ' Error &gt; '. $error _msg. ' &lt;/p&gt; ';


?&gt;


&lt;!--$_server[' Php_self '] invokes its own PHP file when submitting a form on behalf of a user--&gt;


&lt;form method = "Post" action= "&lt;?php echo $_server[' php_self '];? &gt; "&gt;


&lt;fieldset style= "width:250px;" &gt;


&lt;legend&gt;log in&lt;/legend&gt;

&lt;label for= "username" &gt;Username:&lt;/label&gt;


&lt;!--If the user has already lost the user name, echo the user name--&gt;


&lt;input type= "text" id= "username" name= "username"


Value= "&lt;?php if (!empty ($user _username)) echo $user _username;?&gt;"/&gt;


&lt;br/&gt;


&lt;label for= "Password" &gt;Password:&lt;/label&gt;


&lt;input type= "password" id= "password" name= "password"/&gt;


&lt;/fieldset&gt;


&lt;br/&gt;


&lt;input type= "Submit" value= "Log in" name= "Submit"/&gt;


&lt;/form&gt;


&lt;?php


}


?&gt;


&lt;/body&gt;


&lt;/html&gt;

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.

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.