A cookie is often used to identify a user.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
The PHP $_COOKIE variable is used to
retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and
display it on a page:
In the following example we use the isset() function to find out if a cookie has been set:
When deleting a cookie you should assure that the expiration date is in the past.
Delete example:
If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button:
Retrieve the values in the "welcome.php" file like this:
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| Download XML Editor |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|