Using Cookies in PHP
By: Andi, Stig and Derick in PHP Tutorials on 2008-11-23
p>ne simple way to maintain data between the different pages in a web application is with cookies. Cookies are sent by PHP through the web server with the setcookie() function and are stored in the browser. If a time-out is set for the cookie, the browser will even remember the cookie when you reset your computer; without the time-out set, the browser forgets the cookie as soon as the browser closes. You can also set a cookie to be valid only for a specific subdomain, rather than having the cookie sent by the browser to the script whenever the domain of the script is the same as the domain where the cookie was set (the default). In the next example, we set a cookie when a user has successfully logged in with the login form:
<?php ob_start(); ?> <html> <head><title>Login</title></head> <body> <?php if (isset ($_POST['login']) && ($_POST['login'] == 'Log in') && ($uid = check_auth($_POST['email'], $_POST['password']))) { /* User successfully logged in, setting cookie */ setcookie('uid', $uid, time() + 14400, '/'); header('Location: https://java-samples.com/index.php'); exit(); } else { ?> <h1>Log-in</h1> <form method="post" action="login.php"> <table> <tr><td>E-mail address:</td> <td><input type='text' name='email'/></td></tr> <tr><td>Password:</td> <td><input type='password' name='password'/></td></tr> <tr><td colspan='2'> <input type='submit' name='login' value='Log in'/></td> </tr> </table> </form> <?php } ?> </body>
The check_auth() function checks whether the username and password match with the stored data and returns either the user id that belongs to the user or 0 when an error occurred. The setcookie('uid', $uid, time() + 14400, '/'); line tells the web server to add a cookie header to send to the browser. uid is the name of cookie to be set and $uid has the value of the uid cookie. The expression time() + 14400 sets the expiry time of the cookie to the current time plus 14,400 seconds, which is 4 hours. The time on the server must be correct because the time() function is the base for calculating the expiry time. Notice that the ob_start() function is the first line of the script. ob_start() turns on output buffering, which is needed to send cookies (or other headers) after you output data. Without this call to ob_start(), the output to the browser would have started at the <html> line of the script, making it impossible to send any headers, and resulting in the following error when trying to add another header (with setcookie() or header()):
Instead of using output buffering (which is memory-intensive), you can, of course, change your script so that data is not output until after you set any headers. Cookies are sent by the script/web server to the browser. The browser is then responsible for sending the cookie, via HTTP request headers, to all successive pages that belong to your web application. With the third and fourth parameters of the setcookie() function, you can control which sections of your web site receive the specific cookie headers. The third parameter is /, which means that all pages in the domain (the root and all subdirectories) should receive the cookie data. The fourth parameter controls which domains receive the cookie header. For instance, if you use .example.com, the cookie is available to all subdomains of example.com. Or, you could use admin.example.com, restricting the cookies to the admin part of your application. In this case, we did not specify a domain, so all pages in the web application receive the cookie.
After the line with the setcookie() call, a line issues a redirect header to the browser. This header requires the full path to the destination page. After the header line, we terminate the script with exit() so that no headers can be set from later parts of the code. The browser redirects to the given URL by requesting the new page and discarding the content of the current one.
On any web page requested after the script that called set_cookie(), the cookie data is available in your script in a manner similar to the GET and POST data. The superglobal to read cookies is $_COOKIE. The following index.php script shows the use of cookies to authenticate a user. The first line of the page checks whether the cookie with the user id is set. If it"s set, we display our index.php page, echoing the user id set in the cookie. If it"s not set, we redirect to the login page:
<?php if (isset ($_COOKIE['uid']) && $_COOKIE['uid']) { ?> <html> <head><title>Index page</title></head> <body> Logged in with UID: <?php echo $_COOKIE['uid']; ?><br /> <a href='logout.php'>Log out</a>. </body> </html> <?php } else { /* If no UID is in the cookie, we redirect to the login page */ header('Location: https://java-samples.com/login.php'); } ?>
Using this user id for important items, such as remembering authentication data (as we do in this script), is not wise, because it's easy to fake cookies. (For most browsers, it is enough to edit a simple text field.) A better solution- using PHP sessions-.
Deleting a cookie is almost the same as setting one. To delete it, you use the same parameters that you used when you set the cookie, except for the value, which needs to be an empty string, and the expiry date, which needs to be set in the past. On our logout page, we delete the cookie this way:
<?php
setcookie('uid', '', time() - 86400, '/');
header('Location: https://java-samples.com/login.php');
?>
The time() - 86400 is exactly one day ago, which is sufficiently in the past for our browser to forget the cookie data.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Send push notifications using Expo tokens in PHP
PHP convert string to lower case
A Basic Example using PHP in AWS (Amazon Web Services)
Different versions of PHP - History and evolution of PHP
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Resume or Pause File Uploads in PHP
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Comments