PHP Cookies are not being set - php

I'm having issues with setting up cookies. The problem is that my cookies aren't even being set, I have setup a test below to see if they are being set but they are never being set. I've even checked in my browser to see if anything is being set, but nothing from my site.
I would like you to help me make my cookies set. I'm not quite sure what to do. Thank you.
Here is my code:
<?php
session_start();
setcookie("ridArray","", time()+3600);
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
}
?>
<head>
</head>
<html>
<body>
<?php
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
} else { echo "not set"; }
?>
</body>
</html>

Here's the problem, from the SetCookie documentation:
Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
You are setting the cookie value to empty string (""). Try:
setcookie("ridArray","not blank value", time()+3600);
The other issue is that when you set a cookie, it will not be in the request headers (accessed via $_COOKIE) until the next page load. This means when you load that page the first time, $_COOKIE['ridArray'] will NOT be set. On subsequent loads, it will be set, and it will be reset every time.
First page load, it won't be set. Refresh, and it will be set.
The easiest way to debug cookies is to use something like Chrome's developer tools or Firefox's FireBug and watch the response headers for the SetCookie header, and the request headers to see what cookies your browser is sending.

Related

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

Set cookie, nothing is being shown

This is taken directly from w3's website. I may not be understanding cookies correctly, but why is nothing displaying?
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
echo $_COOKIE["user"];
Your cookie will only be accessible when you refresh the page or navigate to a new one.
When your script loads, the HTML header fields for that page have already been set. The page will need to be rendered again (another HTTP transaction) before your cookie is available for use. Check PHP's documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
check that your browser allows localhost / 127.x.x.x cookies or not ? if it allows then refresh the page. If you are using Google Chrome then you can see all browser cookies from here : chrome://settings/cookies navigate to localhost / 127.x.x.x to see your code has put cookies or not !
The variable $_COOKIE[] representates the state at the start of the script. That means that you have to wait on the next page request to see the variable. You could also add your variable manually to the global cookie variable $_COOKIE['user] = 'Alex Porter'; but the problem is that you are not sure that the browser really accepted the cookie.

Check if a PHP cookie exists and if not set its value

I am working on a multilingual site so I tried this approach:
echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
setcookie("lg", "ro");
echo $_COOKIE["lg"];
The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.
Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.
How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.
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'];
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Source
If you set a cookie with php setcookie you can see the set and the value of the cookie, as an example, with the developer tools of firefox just in time.
But you need to reload/load the same/next page if you wanna read, get or check the cookie and the value inside to work with that cookie in PHP.
With this example you can choose if you wanna reload the same page with PHP, HTML or JAVASCRIPT.
If the cookie is not accepted or cookies are disabled, a loading loop is obtained and the browser stops loading the page.
LONGVERSION WITH PHP 'header' RELOAD SAME PAGE:
<?php
$COOKIE_SET = [
'expires' => '0'
,'path' => '/'
// ,'domain' => 'DOMAIN'
,'secure' => 'true'
,'httponly' => 'true'
// ,'samesite' => 'Strict'
];
$COOKIE_NAME = "MYCOOKIE";
$COOKIE_VALUE = "STACKOVERFLOW";
if(!isset($_COOKIE[$COOKIE_NAME])){
setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
// YOU NEED TO RELOAD THE PAGE ONCE
// WITH PHP, HTML, OR JAVASCRIPT
// UNCOMMENT YOUR CHOICE
// echo '<meta http-equiv="refresh" content="0;URL=/">';
// echo '<script>window.location.replace("/");</script>';
header("Location: /");
exit;
}
else{
echo ($_COOKIE[$COOKIE_NAME]);
}
?>
SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE:
if(!isset($_COOKIE['MYCOOKIE'])){
setcookie('MYCOOKIE', 'STACKOVERFLOW');
header("Location: /");
exit;
}
echo ($_COOKIE['MYCOOKIE']);

Cookies cannot be set the first time after clearing history in Firefox

I am trying to setup a session management with cookies in PHP.
My code is as follows:
if(empty($_COOKIE )) {
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
I will then check session_id for 0 and print an error message if cookies are disabled.
This works fine if cookies are really disabled.
The problem is, if a user clears his history the first time he visits
the site he will get the error message even if cookies are enabled.
Anyone have any clues about this ?
Thank you in advance
When you do the setcookie call, the cookies will be sent when the header is output to the browser. This means the cookie won't be available until the next page load (when the client sends the cookie back to the server). This is mentioned in the php manual for setcookie http://php.net/manual/en/function.setcookie.php:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
You won't be able to determine if cookies are enabled/disabled until the page has reloaded (from php). I think you'll have to do this check with javascript, or to stay in php do a redirect after setting the cookie for the first time, something like:
if(empty($_COOKIE)) {
if (isset($_GET['cookieset'])) {
// do error message, cookie should be set
}
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
header('location: http://mysite.com/index.php?cookieset=1');
exit;
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
#bencoder : I have done the test on iPad and Chrome/PC : you are right for iPad, you do need to refresh the page before you can read the cookie data, but on Chrome/PC, after deleting all cookies, if you set a new one from PHP, you can perfectly get the values directly on the first page load. Why ? There must be a more precise explanation. Why two different behaviors? Does the order of this output/availability of the data depend on the browser request to the server? Interesting to know...

Test for cookies in PHP

What is the best way to tell if someone has cookies enabled in their browser. I tried:
<?php
setcookie('cookies','yes',time()+7200);
if (!isset($_COOKIE['cookies'])) {
echo '<div class="error" style="float:right;">You must enable cookies and Javascript to use this site.</div>';
} else {
echo '';
}
?>
but sometimes it displays the alert even if cookies are enabled. I only want an alert if cookies are NOT enabled.
The reason that your code doesn't work is because cookies are sent with the request. The code you're trying will work, but setcookie has to be in a different request than the isset call. Try calling a redirect in between calling those 2 functions.
It is because your cookies are set at the same time as your request is sent to the browser.
It means that even if setcookie() is executed before the script ends the cookies are set after the browser received the request.
To do in a such way, you would need to redirect to a page with a trivial argument and then check for cookies.
A more flexible solution would be to check in javascript.

Categories