HOW TO SETUP COOKIE IN PHP

Date : 31/01/2019

Introduction

A cookie is a small file, that stores in the user computer, used to keep track of information, such as username or else, the site can retrieve when the user visits the website next time.

Setting up cookie using PHP

setcookie() method is used to set up the cookie in PHP. we should call setcookie() method top of the script, before adding any functionality in the script.

Syntax:

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

Note:

name => Name of the cookie

value => value of the cookie,

expire => specifies when the cookie is expired. after the mentioned time the cookie will inaccessible, the default value 0.

path => specifies the path of the server. if we set “/” the cookie is available in the entire domain.

domain => specifies the domain of the cookie(eg. www.mydomainname.com)

secure => It will represent the cookie will be transmitted over secure https protocols.

<?php
$cookie_name = "user";
$cookie_value = "michel";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 
?>

Verify cookie

$_COOKIE variable is used to retrieve the cookie.

<?php
$cookie_name = "user";
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie not exists";
} else {
    echo "Cookie exists";
    
}
?>

Conclusion

Thank you for using pheonixsolutions.

If you like it, share it with your friends.

Leave a Reply