Last updated on September 12, 2023 by Arshad Ullah
We can use the PHP built-in function isset() in conjunction with an if statement to check whether a cookie is set or not. Let’s try to understand with the help of an example.
Example 01:
Look at below example in which we are checking whether the cookie is set or not.
// check if a cookie named "user_name" is set
if(isset($_COOKIE["user_name"])) {
echo "The user_name is set!";
}else{
echo "The user_name is not set.";
}
// output: The user_name is not set.
In the above example, we use PHP built-in function isset() to check if the cookie name user_name is set in the user’s browser. So if the cookie named user_name exists within the $_COOKIE superglobal then if
statment will be true otherwise it will be false.
This function will return us true if the cookie is set or if the cookie is not set it will return us false.
Example 02:
In this example, we set a cookie named user_name
with value John.
setcookie("user_name", "John");
if(!isset($_COOKIE["user_name"])) {
echo "Sorry, cookie is not found!";
} else {
echo $_COOKIE["user_name"];
}
The expected output will be
John
In the above example, we set cookie named user_name with value John. Then we checked if it exists through isset() function. So if the cookie exists the if statement will be true otherwise it will be false.
Conclusion:
This article explains how to check if a cookie exists or not. To check for the existence of a cookie, you can use the PHP built-in function isset() in conjunction with an if statement. If the cookie key exists within the $_COOKIE superglobal, the condition will be true, and the code within the if block will be executed.