Check if a PHP cookie exists and if not set its value
Answer
You can't 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.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
Work around
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
How would I test if a cookie is set using php and if it's not set do nothing
Use isset
to see if the cookie exists.
if(isset($_COOKIE['cookie'])){
$cookie = $_COOKIE['cookie'];
}
else{
// Cookie is not set
}
Checking if Cookie is empty or set in php not working?
You need to use setcookie()
Example:
setcookie("uservalue", "some-value", time()+3600, "/", "example.com", 1);
After setting the cookie, you can check if it's empty:
if (!empty($_COOKIE["uservalue"])){
echo "<span style='color: white'> cookie isn't empty </span>";
}
empty
is true
on the following conditions:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Check if cookie is set
make a new page with this code
if (isset($_SESSION['ID']))
{
if (isset($_COOKIE['cookie'])
{
$ip = get_ip();
$yourbrowser= $ua['name']. " " .$ua['version'];
$req = $bdd->prepare('SELECT * FROM cookies WHERE hash_username = :hash, IP = :IP, browser = :browser');
$req->execute(array('hash_username' => md5($_SESSION['username']), 'IP' => $ip, 'browser' => $yourbrowser));
if ($req->fetch())
{
$_SESSION['ID'] = $data['ID'];
$_SESSION['username'] = $data['username'];
$_SESSION['stat'] = $data['stat'];
}
$req->closeCursor();
}
}
and include it in every page . after that you will not need to write your code again and again.
Check if a PHP cookie exists not worked
force $_COOKIE['mycookie'] for affect immediatly
<?php
if (!empty($_POST['submits'])) {
setcookie('mycookie', 'value', time()+ 36);
$_COOKIE['mycookie'] = 'value'; // <----
}
?>
<form action="" method="post">
<?php
if (empty($_COOKIE['mycookie'])) {
echo '<input type="submit" value="Up+1" id="submit" name="submits">';
} else {
echo 'NotSet';
}
?>
</form>
PHP To check if cookie is there, equal to NULL, or exists
$_cookie
should be caps. Change it to $_COOKIE
and it should work.
Javascript - Check if cookie is set
Here is a function for get the cookie value in javascript.
mycookieValue = getCookie("mycookieName")
if(mycookieValue)
{
//Your code here
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
Check for Cookie existance, if yes do whatever, if no set a cookie
You can use getCookie and setCookie Functions
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Example
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
Reference: W3Schools https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
how to know a cookie is set or not in cakephp
@ sudhir
@ newRehtse
since when can use you methods in isset() or empty()?
thats news to me..^^
so correct would be
if ($this->Cookie->read('somevalue') !== null) {}
Related Topics
How to Add a Method to an Existing Class in PHP
Regex Ignore Url Already in HTML Tags
Problem with Adding Root Path Using PHP Domdocument
How to Create a Logfile in PHP
Mssql Query Issue in PHP and Querying Text Data
Combine 2-3 Transparent Png Images on Top of Each Other with PHP
Phpunit Best Practices to Organize Tests
Wordwrap/Cut Text in HTML String
How to Implement Single Sign-On (Sso) Using Microsoft Ad for an Internal PHP App
Array Merge on Multidimensional Array
How Is Output(Echo) Array Without Use of JSON_Encode(Codeigniter)
Transpose a PHP Multidimensional Array with Predefined Keys
Header("Location") Causes [500] Internal Server Error