I am trying to store array to cookie. I am storing my array products item in cookie array, but it throws error.
$products = array();
$item = array($id => $name);
print_r($item);
$products[] = $item;
setcookie('products',json_encode($products),strtotime( '+1 day' ));
var_dump($_COOKIE['products']);
The above code prints
Array (
[4] => Rug Rat ) Notice: Undefined index: products in
D:\xampp\htdocs\projects\includes\classes\products.php
on line 43 NULL
Cookies are set when the response is sent to the client. This means that you won't be able to access them from PHP code until the next request. See the documentation for setcookie() function, section Common Pitfalls:
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);.
http://php.net/manual/en/function.setcookie.php
So, unless you echo anything, or do anything else that causes the response headers to be sent, you should see var_dumped cookie content after you refresh the page. In your code, there's print_r($item); before setcookie() is called, so you're probably getting a headers already sent warning, and the cookie is never set.
One way or another, it's rarely safe to assume that an array index is set, especially in a superglobal, like $_GET, $_POST, $_COOKIE, etc. You should always check with isset() or array_key_exists if the index is really set.
Related
Hi I tried saving a cookie like the code below
$response = setcookie( "close_pop_up", true, $expiry);
and the response was TRUE. I also check the browser for the said cookie and it's existing. But when I refresh the browser and check for the cookie again although its still present in the browser it seems that I can't retrieve this value using the code below
isset($_COOKIE['close_pop_up']) && $_COOKIE['close_pop_up']
Upon using xdebug the variable close_pop_up is not under the $_COOKIE variable. May I know what I'm missing here?
Note: Cookie value still exist on the browser but can't be retrieve.
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']);
When a user returns to my website, it attempts to restore their last session from the $_COOKIE associative array. It's not working as expected. I can look in my browser's cookie manager and see that the cookies are there, but they don't seem to be getting saved to the $_SESSION associative array.
This is essentially the program flow when a user returns to my site:
foreach ( $_COOKIE as $name => $val )
{
$_SESSION[$name] = $val;
}
session_start();
...
$some_var = $_SESSION[$var_name];
Do I have things out of order, or should I not be overwriting PHPSESSID? Any insight as to what I'm doing wrong would be appreciated. Thanks.
You're getting sessions and cookies mixed up. You don't need to put things into the $_COOKIE array. Just use session_start() and then put things into $_SESSION. PHP will automatically then manage the session/cookie for you.
$_COOKIE variables are stored on the users browser, so they aren't secure and can be manipulated by the user => security risk.
$_SESSION variables are stored only on the server. The only thing stored in the cookie is a session_id, so $_SESSION variable can't be manipulated.
Does that make sense?
Put session_start() before anything else; this function initializes the session data that you will be accessing in $_SESSION.
Not exactly sure what you're trying to achieve with the rest of it all, but session_start() first is a starting point...
I'm trying to do load testing using JMeter 2.5.1. The application is written in PHP, and uses the standard cookie-based session management with a named session. Currently, the test plan is a very simple 2 HTTP request and 1 Cookie Manager within 1 Thread Group. The Cookie Manager's cookie policy is set to compatibility as suggested by the tutorials. However, the session still gets lost on each request.
On the first page call, the session is initialized. I printed the following info before and after the session_start call:
before session start:
session_name() = 'PHPSESSID'
session_id() = ''
$_COOKIE = array (
)
after session start:
session_name() = 'sasExtSMSESSID'
session_id() = 'ihl8svsbl76au7h1ccn3c0ci61'
$_COOKIE = array (
)
On the second page call, the session is supposed to have already been set. But it seems that the cookie that JMeter's cookie manager is corrupted:
before session start:
session_name() = 'PHPSESSID'
session_id() = ''
$_COOKIE = array (
'sasExtSMSESSID' => 'ihl8svsbl76au7h1ccn3c0ci61, sasExtSMSESSID=ihl8svsbl76au7h1ccn3c0ci61',
)
after session start:
session_name() = 'sasExtSMSESSID'
session_id() = '2ro2bkd3t3liq76h7lqn603gm7'
$_COOKIE = array (
'sasExtSMSESSID' => 'ihl8svsbl76au7h1ccn3c0ci61, sasExtSMSESSID=ihl8svsbl76au7h1ccn3c0ci61',
)
So it seems that the cookie array is corrupted somehow, and as the session id is invalid a new one is generated. Beyond calling session_name() and session_start(), there is nothing special in the application that deals with cookies. Accessing the pages using browsers also works. So I guess I didn't configure the JMeter correctly. Any idea what could have caused this? Any help is greatly appreciated.
I'm not sure if this is really an answer, since I still have no idea what is happening, but I guess this is a solution that others may benefit from.
Changing the Cookie Manager's policy from compatibility to default lets me to sidestep this issue, since the corruption apparently happens to another part of the cookie variable:
session_name() = 'sasExtSMSESSID'
session_id() = 'gknq98q7fpecjciti3da9l6mj7'
$_COOKIE = array (
'$Version' => '0',
'sasExtSMSESSID' => 'gknq98q7fpecjciti3da9l6mj7',
'$Path' => '/, sasExtSMSESSID=gknq98q7fpecjciti3da9l6mj7',
)
So far having that $Path corrupted has produced no adverse effect.
Would still appreciate anyone explaining to me exactly what is happening here.
I'm having trouble setting cookies on the same page. I used cookies on my site and it works fine, I tend to set make the php in separate file. Now, I'm setting a cookie on the same page but it doesn't seem to work.
$expire = time()+5;
setcookie("rb_vote", 1, $expire);
then check if it is set
if(isset($_COOKIE["rb_vote"])) {
echo "IS SET";}
else {
echo "IS NOT SET"; }
It always says is not set. I tried doing this in page load but still doesn't work.
See the manual on setcookie() (emphasis mine):
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
Here is a workaround suggestion. It's imperfect because it can't guarantee the cookie actually gets set, but might do in your case.
I've just encountered this issue in Vanilla Forum. On the first page load, before a session has been established, a session cookie is created, but then every time the application wants to access the session variables (to add to them) it looks for the current session ID in $_COOKIE, which is not set until the next page load.
My workaround is to set the $_COOKIE element manually when the cookie is created.
// Create a cookie to identify the session.
// This line already exists. $Name is the cookie name.
// $SessionID is a random md5 ID that has just been generated.
setcookie($Name, $SessionID, $Expire, $Path, $Domain);
// Set the cookie for the remainder of the page. This is a workaround.
if (!isset($_COOKIE[$Name])) $_COOKIE[$Name] = $SessionID;
I've raised this as a fault with Vanilla (https://github.com/vanillaforums/Garden/issues/1568), as this workaround feels like a bit of a hack, but it certainly gets around the problem for now.
PHP5.3 Vanilla Forum Version 2.0.18.4