Cookies in PHP explained. Easy to use function

Submitted on: 1/1/2015 5:57:00 AM
By: Piotr Sienkiewicz (from psc cd)  
Level: Beginner
User Rating: By 13 Users
Compatibility: PHP 3.0, PHP 4.0
Views: 2470
     Cookies in PHP can sometimes be a huge pain in the butt. This function is simple, and teaches you how cookies work, how to write them, expire them, and check their values. Use this cookie for whatever you want, but feedback is always appreciated :o)


setcookie() is the main function that is used to work with cookiesin PHP

parameters are as follows:

setcookie (string name , string value , int expire , string path , string domain , int secure)

Cookies are sent to the user's computer thru the header: in static files, because this is the case you must set, expire your cookies before displaying anything thru your script.. before any echo() and/or print() functions. This is not a PHP setback, it the way HTML works :o) Check out this simple function i have written. . .

function cookie($function, $value) {

if ($function == "set") {

setcookie ("CookieValue", "$value", time() + 14400);// Cookie is Valid for 4 hours. 3 value in function is the time expiration in seconds. ... 3600 seconds = 1 hour

return true;// cookie set, return true

} else if ($function = "logout") {

setcookie ("CookieValue", "$value", time() - 14400);// Cookie is now expired as we set the expiration value to 4 hours ago
return true; // logout complete

} else if ($function = "check") {

if (isset($CookieValue)) {
if ($CookieValue == $value) {
print("ALL GOOD.. cookie verified");
return true;
} else {
print("Value does not much cookie");
return false; // Failed, so return false

} else {

return false;// Failed, since no operations match




Other 1 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.