Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a PHP cookie exists and if not set its value
In PHP, cookies are available only on subsequent page loads after being set. However, you can check if a cookie exists and set it if it doesn't using isset() with the $_COOKIE superglobal.
Understanding Cookie Behavior
According to the PHP manual: "Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays." Cookies are response headers sent to the browser, and the browser must send them back with the next request, making them available only on the second page load.
Checking and Setting Cookies
You can work around this limitation by manually setting the $_COOKIE variable when calling setcookie() −
<?php
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
?>
Complete Example
Here's a more comprehensive example that demonstrates cookie checking and setting −
<?php
// Check if the 'user_language' cookie exists
if(!isset($_COOKIE['user_language'])) {
// Cookie doesn't exist, set it with a default value
setcookie('user_language', 'english', time() + 3600); // Expires in 1 hour
$_COOKIE['user_language'] = 'english';
echo "Cookie 'user_language' was not found. Setting it to: " . $_COOKIE['user_language'];
} else {
// Cookie exists, use its value
echo "Cookie 'user_language' exists with value: " . $_COOKIE['user_language'];
}
?>
Key Points
- Use
isset($_COOKIE['name'])to check if a cookie exists - Call
setcookie()before any output to the browser - Manually set
$_COOKIE['name']to use the value immediately - Remember that
setcookie()only takes effect on the next page load naturally
Conclusion
While cookies are normally available only on subsequent page loads, you can check their existence with isset() and manually populate $_COOKIE when setting new cookies to use them immediately.
