HOW TO SETUP COOKIE IN PHP

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.

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.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Reply

Scroll to Top