Beginners PHP Tutorial – Using Cookies
November 14, 2008
For users who prefer to learn PHP visually we have a range of video tutorials, this method of training greatly enhances learning and allows beginners to master PHP at their own pace.
View the PHP Tutorial Videos – Beginners
Beginners PHP Tutorial – Cookies – Setting and Reading
A cookie is a small text file that is sent by a web server to a web browser and from the browser back again to the server whenever the server requests it.
Cookies are used for many purposes including authenticating logged-in users, tracking shopping cart contents, maintaining user site preferences and more.
A cookie consists of two parts. The cookie name is used to identify the cookie from other cookies sent by the same web server. The cookie value is the actual data that the web server writes to the user’s hard drive. That data is contained within a file using the cookie name.
How to Create a Cookie Using PHP
You can use the built-in SetCookie() function to create a cookie from within your program. This function takes up to six parameters. Only the first two are required. Those are Name and Content. A cookie must be sent before any other content is sent to the browser or an error will result and the cookie will not be written. Here is how you use the function:
How To Send a Cookie to the Browser
If you want to send a cookie to the browser you can use the setcookie() function. Note that you should call setcookie() before any other output statements. The following script shows you how to set cookies:
<?php
setcookie("UserName","JoeGreen");
setcookie("CartID","1234567");
?>
In the above example, the script set two cookies. The first one, named UserName, wrote the site user’s login name to a file. The second cookie, named CartID, wrote that user’s shopping cart ID to a file. Later, when the user is checking out, the server can retrieve both of these files and use the information to help the user pay for his order.
Here’s how you retrieve and read a cookie using the built-in global variable named $_COOKIE array.
<?php
if (isset($_COOKIE["UserName"])) {
$UserName = $_COOKIE["UserName"];
print("Welcome ”.$UserName.” You are logged in\n");
} else {
print("Please log in.\n");
} ?>
When does the cookie crumble?
Unless you take steps to make a cookie persistent, it is automatically deleted when the user closes their browser. Here’s how you can make a cookie stick around longer:
This example will keep a cookie live for 7 days:
setcookie("CartID","1234567",time()+(86400 * 7));
The above code is taking the current time, retrieved using the PHP function time(), and then multiplying the number of seconds in a 24-hour day (86,400) by the number of days in a week (7). That number is added totime() and results in a date seven days in the future.
How to Delete a Cookie
You can delete a cookie, regardless of whether it is temporary or persistent, simply by changing its expiration date to a time in the past. Here is an example:
setcookie("CartID","",time()-1);
Once you execute that line of code, the cookie immediately expires.
Here is a description of all the parameters that SetCookie() accepts:
setcookie(name,value,expire,path,domain,secure)
- Cookie name: (already demonstrated)
- Cookie value: (already demonstrated)
- Cookie expiration date/time: (already demonstrated)
- Cookie path: If set to “/”, the cookie will be available throughout the entire site path structure. If set to “/cart/”, the cookie can only be accessed when the user is in the /cart/ directory and any of its sub directories. The default value is the directory that the cookie was originally set in.
- Domain: Specifies the domain name that the cookie is available in. To make the cookie available on all sub domains of MySite.com, you would set this parameter to “.mysite.com”. If you set it to www.mysite.com, then it is only available when they in the WWW portion of the domain. So, if you had mycart.mydomain.com, you could not read the cookie.
- Secure: Determines whether the cookie can be created and read in an insecure connection, or only when the user has created an HTTPS connection. Set it to TRUE to force a secure connection. The default is FALSE.
For users who are just getting started with PHP, Cheat Sheets can be an excellent way to learn, this link is an excellent resource on not only PHP Cheat Sheets but also CSS and HTML. PHP Cheat Sheets
Entry Filed under: PHP. Tags: Beginners PHP Tutorial, cookies and sessions, php tutorial setting cookies.
Trackback this post | Subscribe to the comments via RSS Feed