Cannot get Cookie - php

Until now i always worked with session in Codeigniter. But now there is to much data for an session. I like to use cookies, but it doesn,t work for me.
I first load the cookie helper in the autoload.
I use this code to add data $this->input->set_cookie('users_new',$users_new);
var_dump($this->input->cookie('users_new')); With this one i tried to get the data. But it is empty. The variabele $users_new is filled with an array, so it cannot be empty.
When i try this simple example, the cookie is alsoempty.
$cookie = array(
'name' => 'some_value',
'value' => 'The Value'
);
set_cookie($cookie);
var_dump(get_cookie('some_value'));
die();
Whats wrong?
Thanks for your help!!

Cookies are sent by the browser so you would have to wait the user reload a page.
So the basic process is:
you set a cookie
the user resend the cookie on the next request
you can access the cookie value using get_cookie
EDIT:
setcookie is used this way, it won't work with an array
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire dans 1 heure */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
so you should do:
foreach ($cookie as $key => $val) {
setcookie($key, $val);
}

You should set an expiration value, i.e. seconds from the moment it gets created to when it will expire.
the "name" value must be a string, not an array. If you want multiple infos, you can just serialize() the array.
Example code:
$cookie = array(
'name' => 'users_new',
'value' => serialize($users_new),
'expire' => '86500'
);
$this->input->set_cookie($cookie);
You don't need to load the cookie helper if you just use the input class. No problem, I know, just to avoid useless lines of code :)

Cookies cannot hold arrays, just plain text. #RageZ had a good clue with the for loop which would set many cookies (as many as vars in array). #Damien suggests "serialized" and another option would be to jSon the array into a str with native php function "json_encode()"

Related

PHP Session Cookie With Security Flags & Extendable Expiry - Best Way?

Okay so I've created a login system using PHP Sessions which stores user-related data within $_SESSION while logged in. To reach a PHP $_SESSION / session cookie whose expiry gets extended by x seconds every time the client refreshes a page, I created the following callback, which I call upon every page initiation:
<?php
if ( session_status() === PHP_SESSION_NONE ) {
session_start(
[
'cookie_path' => '/',
'cookie_domain' => 'mydomain.com',
'cookie_secure' => true,
'cookie_httponly' => true,
'cookie_samesite' => 'Strict',
'use_strict_mode' => true,
'use_trans_sid' => false,
'use_only_cookies' => true
]
);
} else {
// If session already exists, simply take it up again without overwriting parameters
session_start();
}
// Then determine the lifetime of the cookie (was only able to make the session cookie
// lifetime expendable using this syntax, as explained in the [first example of the php docs](https://www.php.net/manual/de/function.session-set-cookie-params.php)
setcookie(
session_name(),
session_id(),
[
'expires' => time() + x,
'path' => '/',
'domain' => 'mydomain.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]
);
?>
The reason why I specify all the:
httponly
secure
cookie path
cookie domain
samesite
parameters upon the very first call of session_start() AND also in the call of setcookie() is because if I specify one of them in session_start() and not in setcookie() or vice-versa, the browser returns two session cookies with the same session IDs, one having all of the mentioned flags, and the other without:
Now the problem is that, when I logout via the following callback, which I call as specified in the docs:
<?php
// Called via PHP Form Submit
session_start();
setcookie(
session_name(),
'',
time() - 42000,
'/',
'mydomain.com',
true,
true
);
session_destroy();
header( 'Location: mydomain.com' );
?>
I get the same problem as described in the images above; two session cookies in my browser, and again one having all the flags set, the other not, and the one without the flags set having set its expiry to the session's end, and the other one with its expiry set in x seconds; all exactly as in the image.
What am I doing wrong?
UPDATE
Is it may better to actually set all of the session cookie parameters via the php.ini file, and handle the session cookie expiry via a timestamp within $_SESSION, done like in this example?? Just thinking of a way of making the provision of any parameters in session_start() + any calls to setcookie() obsolete..
So my question is basically:
What's actually the best way of using several PHP session cookie flags, combined with a session expiry which is limited to let's say 10 mins, which gets refreshed by 10 mins on every page load?

Cookie not setting in php version 7.4 using option array?

I am trying to get my a cookie to work within an iframe on another site url.
But when I add this new method of setting cookie options in an array, the cookie is not setting at all even not viewing in the iframe.
Here is my previous php set cookie which works fine on its own url, but does not work in iframe.
public function authenticate()
{
$this->loadCrypt();
setcookie(
'_siteauth',
Crypt::encrypt(site()->password),
time() + 86400,
'/'
);
return true;
}
Then here is my new version thats not working when outputting options as an array as per php docs for 7.3 above.
public function authenticate()
{
$this->loadCrypt();
setcookie(
'_siteauth',
Crypt::encrypt(site()->password),
[
'expires' => time() + 86400,
'path' => '/',
'samesite' => 'None'
]
);
}
The syntax above is exactly the same as the one in this question...
How to fix "set SameSite cookie to none" warning?
I'm getting no errors, the second set cookie method is not even setting a cookie, when the first one at least sets, just not when not inside an iframe on a different domain.
Any ideas would be great thanks.
Checked response header and there is a warning icon against Set-Cookie which I didn't have originally. But it doesn't tell me what the error is and why?

How to create lifetime session in yii2

I have started using Yii2 basic and need to store session information. I already know that in Yii2 basic, this should be done using sessions like
$session = Yii::$app->session;
$session->open();
$_SESSION["a_id"] = $id;
$_SESSION["w_auth"] = "true";
The problem with this is that every time the browser is closed my session expire
Is there anyway to keep session alive or set session destroy so even I close the browser and open it again. It will not ask me again to put my username or password.I need to do this in the YII2 Basic .
session cookies set expire time after 7 days
`
'components' => [
'session' => [
'class' => 'yii\web\Session',
'cookieParams' => ['lifetime' => 7 * 24 *60 * 60]
],
`
You need to use cookies for this.
Cookies are info kept in your browser.
Here is how to do in yii2:
$cookies = Yii::$app->response->cookies;
// add a new cookie to the response to be sent
$cookies->add(new \yii\web\Cookie([
'name' => 'a_id',
'value' => $id,
]));
Add the above cookie when you login and then use it this way in your actions:
$cookies = Yii::$app->response->cookies;
$a_id = $cookies->getValue('a_id');
if($a_id !== null) {
// user is logged in
}
Note: What is kept in the cookie of your browser is not your actual info, but the session id and this is sent when you reopen your browser and restores your session by this id. Your actual info is kept in your session(in the server). This how yii 2 cookies work.
References
What are cookies and sessions, and how do they relate to each other?
Cookies vs. sessions

Codeigniter Cookie Issue

Cookies arent being set in my first view.
Is this how it should be ? or am I mistaken
Please view the code below for further illustration:
if( !get_cookie('rate') ){
$cookie_rate = array(
'name' => 'rate',
'value' => '10',
'expire' => '100000'
);
set_cookie($cookie_rate);
}
var_dump( get_cookie('rate') ); //returns ( boolean false )
if( !isset($_COOKIE['foo']) ){
$_COOKIE['foo'] = 'bar';
}
var_dump( $_COOKIE['foo'] ); // This yields string 'bar' (length=3) on the first visit
Doing the same thing with php cookies yeilds an array with cookie values.
This problem persists only in the first visit of a page.
This isn't a CodeIgniter vs PHP issue. You just don't understand how cookies work.
Cookies are a header sent by the server which the browser must send back on subsequent requests. $this->input->set_cookie() and set_cookie() send a cookie header.
$_COOKIES on PHP (and thus $this->input->cookie() and therefore the get_cookie() helper) only contain cookies which the browser sent.
Thus when you set a cookie with set_cookie(), you won't be able to get_cookie() until the browser's next request.
Seeing as CI's set_cookie probably utilizes the same mechanism as PHP's setcookie(), this entry from the manual probably applies:
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);.
I can't see any mention of this behaviour in the CI manual, but it's likely to be the same thing.
If I understood this right youre trying to see the data of the cookie before reloading the page which won't work. Try setting the cookie, reloading the page and then checking the cookie for data.
Also sometimes you need to specify domain and such, perhaps it doesn't apply right now but it might be nice to know later if they suddenly stop working, from CI-documentation:
$cookie = array(
'name' => 'The Cookie Name',
'value' => 'The Value',
'expire' => '86500',
'domain' => '.some-domain.com',
'path' => '/',
'prefix' => 'myprefix_',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
Also, consider using the session class instead of cookies if you don't need anything specifically from cookies since they are more secure. http://codeigniter.com/user_guide/libraries/sessions.html
Thats probably not the problem, in fact thats how cookie works, its set and on next page load it seems to be visible from then.

Cookie - Why cookie showing in browser after it deleted by using PHP code

Why cookie values showing in browser even after it deleted by using PHP code, I am viewing cookie values by using FireFox "View Cookies addon". It will disappear only after delete or clear my browser cookies manually. I asking this question because of my work will work only after deleting cookies from browser manually, if i unset cookie in PHP code and run , it will not work, i am un setting cookie value by setting its expire date with past value.Example:
setcookie ("myCookie", "", time() - 3600, "/", ".example.com");
Code I am using for setting cookie:
setcookie ('Event', '', time() - 3600, '/', '.example.com');
Code I am using for unsetting cookie:
setcookie('Event', '-1-1301223453%7C9de8f7c08bf2be19c125f86ced33a0c2%7C1301050653%7C-1%7C1301223453', '', '/', '.example.com', 0);
But if i print cookie value after it unset it will be blank(nothing), but it will show in browser
Please any one help!!
That is completely based on browser settings you are viewing in and you are asking that the browser is still showing the cookies. That is true browser is still showing the cookies but you will get relax when you check it in PHP the cookie is unset.
print_r($_COOKIE);
show you the active cookies.
Remember when you clear cookies from your browser tool then cookie will be erased but when you unset from the PHP they are set to the time in past not erased from browser history.
Delete cookie with setcookie("myCookie");
What about trying this approach?
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
This could have various reasons. First of all, check if the cookie is set at all. Then make sure it uses the same parameters (except the expiration) as when the cookie was originally set. And for the expiration parameter, use a value that is definitely long in the past (one hour could be too little if your server’s time is off by some hours):
setcookie($cookieName, 'deleted', 1, $cookiePath, $cookieDomain);
here is a simple tutorial about delete cookie by php
first we set the cookie value and expire date.
setcookie('test', 'test', time() + 3600);
visit the page, you'll see the cookie 'test' has successfully created
then, we change the php code to delete cookie 'test', just set a passed date value for it
setcookie('test', 'test', time() - 3600);
visit the page again, you'll find the cookie 'test' has gone
btw: i was use the fire cookie extension to check the cookie value.
hope this simple tutorial can help you.

Categories