Can cookies be deleted? Guide to using Cookies in PHP

Source: Internet
Author: User
Tags setcookie
Review
A cookie is a way for a server or script to maintain information on a client workstation under the HTTP protocol. A cookie is a small file saved by a Web server on a user's browser that can contain information about a user, such as an identification number, a password, how a user purchases on a Web site, or the number of times a user visits the site. The Web site can access cookie information whenever a user is linked to a server.
How do I set up cookies?
You can use the Setcookie function to set a cookie in PHP. Cookies are part of the HTTP header, so setting the cookie feature must precede any content being sent to the browser. This restriction is the same as the header () function. Any cookie from the client will automatically be converted to a PHP variable. PHP obtains the information header and parses it, extracts the cookie name and changes it into a variable. Therefore, if you set a cookie such as Setcookie ("MyCookie", "cookies") PHP will automatically generate a variable named $mycookie with a value of "cookies".
Let's take a look at the Setcookie function syntax:
Init Setcookie (String cookiename,string cookievalue,int cookieexpiretime,path,domain,int secure);
Parameter description:
PATH: Represents a directory on the Web server, default to the directory where the page is called
Domain:cookie the domain name that can be used, which defaults to the domain name of the called page. This domain name must contain two ".", so if you specify your top-level domain, you must use ". MyDomain.com"
Secure: If set to "1", the cookie is only remembered by the server that the user's browser considers to be secure.
Examples of use of cookies
Suppose we have a site that needs to be registered, it automatically identifies the user and takes action: if it's a registered user, send him a message, or if it's not already registered, a link to the registration page is displayed.
In accordance with the above requirements, we first create a database to save the registered user information: First name, last name, email address (visit counter).
Follow the steps below to build the table:
mysql> CREATE database users;
Query OK, 1 row affected (0.06 sec)
mysql> use users;
Database changed
mysql> CREATE TABLE info (FirstName varchar), LastName varchar (+), e-mail varchar (+), Count varchar (3));
Query OK, 0 rows affected (0.05 sec)
Then build a PHP page to check the cookies against the database.
Since PHP can convert a recognized cookie into a corresponding variable, we can check for a variable named "Mycookies":
? if (Isset ($myCookies)) {//If the cookie already exists
......
} else {//If the cookie does not exist
......
}
? >
When a cookie is present, we perform the following steps:
First get the cookie value, use the Explode function to analyze the different variables, add the counter, and set a new cookie:
$info = Explode ("&", $myCookies);
......
$count + +;
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Mycookies", $CookieString, Time () +3600); Set cookies
The user information is then output using an HTML statement.
Finally, update the database with the new counter value.
If this cookie does not exist, we display a link to the registration page (register.php).
The following register.php is the user registration page:
/* register.php */
<form method= "POST" action= "regok.php" >
First Name:<input type= "text" Name= "FirstName" >
Last name:<input type= "text" Name= "LastName" >
<input type= "Submit" value= "register" >
</form>
The information that the user fills in on the Register.php registration page is submitted to regok.php:
/* regok.php */
if ($FirstName and $LastName and $email) {
...//query whether the user exists in the database
}
}else{
...//error handling
}
The above program flow is as follows:
First check that all information is filled in as required, and if not, return to re-enter
If all the information is filled out, first, we retrieve the user login details from the database
Mysql_connect () or Die ("Connection Database Error! ");
$query = "SELECT * from info where firstname= ' $FirstName ' and lastname= ' $LastName ' and email= ' $email '";
$result = Mysql_db_query ("Users", $query);
$info =mysql_fetch_array ($result);
$count = $info ["Count"];
Check whether the database has such a user, if any, it specifies the old information, and uses the current information to build a new cookie, if the same user does not have a database login, create a database login, and build a fresh cookie.
Now use the Isset () function to check if the user has a counter, increase the counter if any, and create a new cookie:
$count + +; Add counter
$CookieString = $FirstName. ' & '. $LastName. ' & '. $email. ' & '. $count;
Setcookie ("Mycookies", $CookieString, Time () +3600);
If you do not have a user counter, add a record to MySQL and set a cookie
Note: Before calling the Setcookie function, there should be no data output to the browser, otherwise an error will occur.
How do I implement a cross-domain cookie?
From the cookie specification, a cookie can only be used for a domain name, so if a cookie is set on a domain name in the browser, the cookie will not be valid for the other domain name.
Let's talk about a cross-domain cookie implementation scenario:
First step: Create a preset script
Add the following code to the preset script (or to a function that precedes all scripts).
<?php
/* If the get variable is already set and it differs from the cookie variable
* Use the Get variable (update cookie)
*/
Global $HTTP _cookie_vars, $HTTP _get_vars;
if (Isset ($sessionid) && isset ($HTTP _get_vars[' SessionID ') && ($HTTP _cookie_vars[' SessionID ']! = $ http_get_vars[' SessionID ')) {
Setcookie (' SessionID ', $HTTP _get_vars[' SessionID '], 0, '/', ');
$HTTP _cookie_vars[' sessionid ') = $HTTP _get_vars[' SessionID '];
$sessionid = $HTTP _get_vars[' SessionID ');
}
? >
After this code is run, a global variable ' SessionID ' will be available for scripting. It will save the SessionID value in the user's cookie, or the SessionID value sent through the GET request.
Step two: Use variables for all cross-domain references
Create a global configuration file that holds the basic reference form for the domain name that can be toggled. For example, if we have domain1.com and domain2.com, the following settings are set:
<?php
$domains [' domain1 '] = "http://www.domain1.com/-$sessionid-";
$domains [' domain2 '] = "http://www.domain2.com/-$sessionid-";
? >
We write a code like this:
<?php
echo "Click <a Href=" ", $domains [' domain2 '],"/contact/?email=yes ">here </a> to contact us.";
? >
The above code will produce the following output:
Click <a Href= "Http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes" >here </a> to contact us.
Here SessionID has been inserted into the URL.
Step Three: Configure Apache
Now, let's configure Apache to rewrite this URL.
We need to
http://www.domain2.com/-66543afe6543asdf6asd-/contact/
Into this:
Http://www.domain2.com/contact/?sessi
And this URL:
Http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes
Into this:
Http://www.domain2.com/contact/?email=yes&sessi
To achieve the above requirements, simply configure two virtual servers as domain1 and Domain2, as follows:
<virtualhost ipaddress>
Documentroot/usr/local/www/domain1
ServerName www.domain1.com
Rewriteengine on
Rewriterule ^/-(. *)-(. *?). *) $ $2&sessi
Rewriterule ^/-(. *)-(. *) $ $2?sessi
</VirtualHost>
<virtualhost ipaddress>
Documentroot/usr/local/www/domain2
ServerName www.domain2.com
Rewriteengine on
Rewriterule ^/-(. *)-(. *?). *) $ $2&sessi
Rewriterule ^/-(. *)-(. *) $ $2?sessi
</VirtualHost>
These overridden rules implement the requirements of the above two URL overrides.

The above describes the cookie can be deleted, PHP in the use of cookies, including the content of the cookie can be deleted, I hope that the PHP tutorial interested in a friend helpful.

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