codeigniter cookie helper combined with session helper - php

Is it possible to run both session and cookie helpers? Cause I am trying and I can't get a cookie to set for the life of me, no matter what method I try either falling CI's docs to the letter and doing it there way or attempting to work with cookies through native php alone. Either way I try cookies will not set.
I have tried to set them like:
$this->input-set_cookie('AutoRemember', $mID.'-'.$hashbrown, $shortlife);
and
setcookie('AutoRemember', $mID.'-'.$hashbrown, $shortlife);
and I have tried to work with them like
echo $this->input->cookie('AutoRemember');
and
echo $_COOKIE['AutoRemember'];
the cookie helper is auto loaded just as is the session one, so they are loaded. session helper works like a charm, but the cookies I got nothing but a headache. All I want to do is set a cookie so I can have a "remember me" function on my site, and what should be a 5 minute deal to do, has taken me hours of various ways of passing it either by setting something for a view to pick up so it can set it in a view, or setting it in the controller and nothing.
Doesn't appear to be a browser issue either as both Chrome, and FireFox seem to not have a cookie getting stored anywhere.
So is it something with using both sessions and cookies or is codeigniter garbage when it comes to setting a cookie and kills the effort no matter which way you try.

Looking through some of the Expression Engine code (an app shipped by Ellis Labs that uses CI) they are calling the PHP native setcookie function in their set_cookie function, so perhaps this is the way to go.
Looks like there should be no problem having the cookie helper running in tandem with the Session library. That said it's worth noting the Session class is calling setcookie directly rather than using the cookie helper (way to reuse code CI!).
In general, calling the PHP function setcookie should bypass any CI stuff and work no matter what, so if that isn't working maybe something else is going on. Best bet is probably to start with setcookie and try to get that working.
Check the return value from setcookie, if it's false output has already been started and that's why it isn't working; could be the same issue you're running into trying the CI cookie helper too.

Related

Cookie::forget not working laravel 5.1

I'm trying to get Laravel 5.1 to delete my cookie, however it will not delete even though i'm returning it with my redirect.
return redirect('/voucher')->withCookie(Cookie::forget($cookie));
Have I done something wrong?
Maybe I am wrong, but you are probably using cookie object in place of cookie name when calling Cookie::forget($cookie). Unless $cookie is a string containing cookie name, you should try something like this:
return redirect('/voucher')->withCookie(Cookie::forget('cookie_name'));
I know this is already an old and answered question but I got here recently and if I'm correct, the cookie needs to be 'queued' for the next response.
You can do that by adding the cookie manually to the response as #Jan.J already described in his answer. But if you need to do it inline, this might also work for you:
Cookie::queue(
Cookie::forget('cookieName')
);
The CookieJar will pass all queued cookies to the next response.
In my case there was an array stored in the cookie, so none of provided methods has worked. Array should be deleted providing exactly pair of array:
Cookie::queue(Cookie::forget('array_name[provide_key]'));
First, make sure you've imported Cookie class with use keyword, like below :
use Cookie;
Next, create a function and delete a cookie by name
Cookie::queue(
Cookie::forget('cookie_name_first')
);
Cookie::queue(
Cookie::forget('cookie_name_second')
);
public function funname(CookieJar $cookie)
session()->flush();
$cookie->queue(cookie()->forget('user_email'));
$cookie->queue(cookie()->forget('user_password'));
return redirect('/');
Unfortunately none of the above worked for me, I'm not sure if it's a specific issue with this version of Laravel (5.1).
I did manage to get it working using raw PHP instead, by overwriting the existing cookie with an already expired one, I also had to specify a path to get this working. It's not as elegant as using a facade however.
setcookie('COOKIE_NAME', time() - 3600, '/');
You can also do it this way:
redirect('/')->cookie(cookie()->forget('my_super_cookie_name'));
Recently I faced this issue while still on localhost but the issue was that I have written some code which weren't normal in my process of trying to overwrite the session config file.
Therefore
The default laravel
Cookie::queue(
Cookie::forget('name')
) ;
Should work perfectly fine if you have not done any changes on your
session.php config file.
Check it out and you should be good to go.
If you have made some changes try to ensure that your code conforms to standard and everything should work fine.
Your code is perfect, so there's some other issue.
Cookies are tricky little ^##$$ and to make things worse are dependent on the client's implementation; various browsers may well handle cookie edge cases differently, or may even have had long-standing bugs relating to their cookie handling.
The "removal" of a cookie actually involves sending an update to the cookie but with an expiration date in the past. From RFC 6265:
Finally, to remove a cookie, the server returns a Set-Cookie header
with an expiration date in the past. The server will be successful
in removing the cookie only if the Path and the Domain attribute in
the Set-Cookie header match the values used when the cookie was
created.
If your Laravel code looks fine, as in the original question, I would suggest inspecting your cookies in your browser's dev tools. For example, Chrome's "Network" tab has a "Cookies" tab which shows you the Request Cookies and the Response Cookies. You may find there is a subtle difference between the original cookie and the cookie being sent to unset it. As per the RFC above, a difference in the domain (even just a leading dot) will break the cookie removal.

Browser Sends Two Cookies - PHP's Session Handler Reads Wrong One

For a period of time cookies were set on a single site with different values for the domain. This resulted in some people having cookies with the same name set for both .www.domain.com and .domain.com. The site is intended to be accessed as www.domain.com. This is accomplished with .htaccess rules.
The code will use .domain.com. now for the session.cookie_domain going forward.
The issue I am having is that when both cookies exist the browser sends both (both are valid). I see this is so in the headers and also when dumping out apache_request_headers(), however, when I dump out $_COOKIE I see just one of them.
["Cookie"]=>
string(74) "foobar=hkej4qdnq5kismiq3kl07qv6k2; foobar=ocvn7anlu2f2k2l37nl9ou3c21"
And then...
array(1) { ["foobar"]=> string(26) "hkej4qdnq5kismiq3kl07qv6k2" }
My session interface read($id) method is checking the old cookie and not the one we set on login.
What is the best way to address this? I am thinking I could just change the session name/identifier and start fresh. Or maybe evaluate the Apache headers in my read implementation. I have not found much that is relevant in searching the web, just a bunch of fluff from w3schools polluting the results, so I thought this might be a good one to post here.
I had the same problem and solved it by changing the session name.
PHP allows you to access the variable $_SERVER["HTTP_COOKIE"] and parse it yourself. This allows you to access both values, of the cookie, but you can still not tell apart the correct and the wrong cookie.
Unless those cookies contain really valuable data, I would not care about the old values and just start new.
Just change the session name from PHPSESSID to SITESESSID or something else of your choice. This will make sure that your application ignores the old cookie all together. If the lifetime of your session is 0, then its a SESSION Cookie(Gets deleted when the browser is closed), in such case you can change the session name back to PHPSESSID after a few days or a month of implementation since you will be sure that no one has the old cookie.
BTW: The browser isn't sending two cookies. It's just your old session cookie still alive.

codeigniter setting session variable with a variable not working

Using codeigniter running locally on WAMP and dealing with sessions. I tried the default session handler, db session, native session and now db session. They all result in the same issue and I can't for the life of me figure it out.
The problem is that I am trying to set a session variable using a variable. I have confirmed the variable and have echoed it out and all is well in the controller. The controller calls on a view and the variable is there as well. The view calls on a uploader file and this is where the variable randomly gets set to "style.css" for some reason. If I set the session statically, say to "randyval", then it sticks. It's only when trying to use a variable that it breaks.
Using db session allows me to set using:
$some_val = $some_otherVal;
$_SESSION['sess'] = $some_val;
Only in the final page does echo $_SESSION['sess'] result in "style.css".
If however I do:
$_SESSION['sess'] = 'test';
Everything works as should.
Wouldn't ask unless I was at my wits ends... thanks for any input.
Color me stupid. :\ Turns out there was some bad html that was causing the problem(?). It had to do with, yeah, you guessed it, the header and more specifically where the "style.css" file was being called. Not sure why that was wrecking the session, but it indeed was. So, sorry for wasting everyones time, you can go home now.
You should work with CI sessions using Session Class
For any of you who stumbled upon this page, see here for the solution :
I solved it this way : Losing a session variable between one page with codeigniter session library

My cookies won't stay (PHP)

I'm building an autologin system using cookies, but one fundamental part of the functionality of the cookies fails: they are non-persistent over different sessions - or even pages!
In my login script, I set the cookies like this:
setcookie('userID', $userID, time()+86400); // (edited after replies)
$userID has a value.
Then I print the $_COOKIE variable and it says array(['base_usid'] => 1); So that's good, but when I click the home page and print the $_COOKIE variable there, it says NULL.
Does anyone see the problem?
Cookies should have a time value for how long they should stay... Check http://php.net/manual/en/function.setcookie.php
In other words, change it to: setcookie('userID', $userID, time()+86400);
to make it stay for a day for example.
Aah, I've learned something new about cookies :) They have a path and they are only available on that path (the directory they were created in). I created the cookies on /user/login, and then tried to read them on /news/index. Won't work.
In the past I used to build websites with all files in just one folder (I know it's bad), so I didn't know of this cookie property. Sorry, I should have read the manual better...
Thanks for your help!
P.s.: Typing print_r($_COOOKIE); won't speed up debugging. :(
Cookies need an expiration time. Otherwise they are by default destroyed when a user closes his browser.
Try this instead
setcookie("userID", $userID, time()+3600);
This will last for an hour. Make the number bigger to have it last longer.
To unset / remove it, change the plus + to a minus -
:)
If its still not working after you've set an expiry time (and you've checked the clocks on server and client are correct) then have you checked that the cookie is being sent? Sounds like the problem with 'headers already sent'. Which would also imply you have a problem with error reporting / logging.
C.
Do you want to learn how to build CMS systems and login managers, or do you want to build an app... ?
Hate to do this, but my answer is : don't build your own login system. Instead, go grab some framework like CodeIgniter, Kohana, or even drupal or Joomla. If you are building a login system as a learning experience to understand how cookies work/etc, then fine.. go ahead.. as long as you don't plan on putting it into some production site. Otherwise, grab a well tested framework and use it.

CakePHP dropping session between pages

I have an application with multiple regions and various incoming links. The premise, well it worked before, is that in the app_controller, I break out these incoming links and set them in the session.
So I have a huge beforeFilter() in my app_controller which catches these and sets two variables in the session. Viewing.region and Search.engine, no problem.
The problem arises that the session does not seem to be persistant across page requests. So for example, going to /reviews/write (userReviews/add) should have a session available which was set when the user arrived at the site. Although it seems to have vanished!
It would appear that unless $this->params is caught explicitly in the app_controller and a session variable written, it does not exist on other pages.
So far I have tried, swapping between storing session in 'cake' and 'php' both seem to exhibit the same behaviour. I use 'php' as a default. My Session.timeout is '120', Session.checkAgent is False and Security.level is 'low'. All of which should give enough leniency to the framework to allow sessions the most room to live!
I'm a bit stumped as to why the session seems to be either recreated or blanked when a new page is being requested. I have commented out the requestAction() calls to make sure that isn't confusing the session request object also, which doesn't seem to make a difference.
Any help would be great, as I don't have to have to recode the site to pass all the various variables via parameters in the url, as that would suck, and it's worked before, thus switching on $this->Session->read('Viewing.region') in all my code!
Try setting the security setting in your /app/config/core.php file to medium or low. That solved a session problem I had.
i had the solution or at least that work for me
you try to pass from controller reviews action write to controller userReviews action add right???
check that your controller userReviews must end whit php tag "?>" and NO MORE SPACE
SO if you have someting like this
line
999 //more code lines
1000 ?>
1001
your session fail
you have to had this
line
999 //more code lines
1000 ?>
sorry for my bad english
soo you
It would appear that unless
$this->params is caught explicitly in
the app_controller and a session
variable written, it does not exist on
other pages.
That sounds like the proper behavior unless you are posting data from page to page. If you want any variable to persist, it should either be set in the model (where it will persist with the association), or passed on in a function, or set in the session explicitly using the session component:
$this->Session->write('Viewing.region');
(see: http://book.cakephp.org/view/398/Methods)
On a related note, I've had most success with sessions stored in the database. Run the file from app/config and set it to db. See if that helps.
Also, do the Cake core tests for the session work?
Might it be this problem? Essentially, cake's session resets if the user-agent changes
It's a shame that I ran into this very problem you mention a few days ago and now I cannot find the link that helped me solve it.
Also: are you using database or plain php sessions?
I'm going to go out on a limb here without being able to look at your code, but might it be possible that your "reviews" controller (or whatever) has its own beforeFilter() and doesn't call its parent's beforeFilter() explicitly?
This has burned me before...
I got some issues like this. Session set using some controller was not available in another , controller . I could clear the issue after spending few hours . There was a white space afer the end of php tag at the bottom . After clearing the line and white space after the last ?>
tag worked fine .
I had this problem when moving a CakePHP site. My problem was that the session directory wasn't writeable. You should make sure the folder app/tmp and all it's subfolders (including sessions) have permission 777.

Categories