Cookie::forget not working laravel 5.1 - php

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.

Related

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 cookie helper combined with session helper

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.

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.

How to re-initialize a session in PHP?

I am attempting to integrate an existing payment platform into my webshop. After making a succesful transaction, the payment platform sends a request to an URL in my application with the transaction ID included in the query parameters.
However, I need to do some post-processing like sending an order confirmation, etc. In order to do this, I'd need access to the user's session, since a lot of order-related information is stored there. To do this, I include the session_id in the intial request XML and do the following after the transaction is complete:
$sessionId = 'foo'; // the sessionId is succesfully retrieved from the XML response
session_id($sessionId);
session_start();
The above code works fine, but $_SESSION is still empty. Am I overlooking something or this simply not possible?
EDIT:
Thanks for all the answers. The problem has not been solved yet. As said, the strange thing is that I can succesfully start a new session using the session_id that belongs to the user that placed the order. Any other ideas?
Not really what you ask for, but don't you need to persist the order into database before you send the customer to the payment-service? It's better to rely on persisted data in your post-processing of the order when you receive the confirmation of the payment.
Relying on sessions is not reliable since you will have no idea on how long this confirmation will take (usually it's instant, but in rare cases this will have a delay).
Also, in the event of your webserver restarting during this time span, will make you lose relevant data.
A third issue is if you have a load-balancing solution, with individual session-managment (very common) then you will have no guarantee that the payment-server and your client will reach the same webserver (since stickiness is usually source-ip based).
I will venture to guess that since domains are different from where the session is set to where you are trying to read it, php is playing it safe and not retrieving session data set by a different domain. It does so in an effort to preserve security in case somebody were to guess session ID and hijack the data.
Workaround for this, assuming the exchange happens on the same physical disk, is to temporary write order data to a serialized (and possibly encrypted depending on wether or not full credit card number is being tracked, which is a whole another story) file that once read by the receiving end is promptly removed.
In essence all that does is duplicates the functionality that you are trying to get out of sessions without annoying security side-effects.
Many thanks for all the replies.
Smazurov's answer got me thinking and made me overlook my PHP configuration once more.
PHP's default behaviour is not to encrypt the session-related data, which should make it possible to read out the session data after restarting an old session from another client. However, I use Suhosin to patch and prevent some security issues. Suhosin's default behaviour is to encrypt session data based on the User Agent, making it a lot harder to read out other people's sessions.
This was also the cause of my problems; disabling this behaviour has solved the issue.
Make sure you're closing the current session before you attempt to start the new one. So you should be doing:
$id = 'abc123';
session_write_close();
session_id($id);
session_start();
Dirty, but has worked for me:
Tell the payment gateway to use
http://yourdomain.com/callbackurl.php?PHPSESSID=SESSIONIDHERE
PHP uses that method of passing a session around itself if you set certain config vars (session.use_trans_sid), and it seems to work even if PHP has been told not to do that. Its certainly always worked for me.
Edit:
Your problem may be that you have session.auto_start set to true - so the session is starting automatically using whatever ID it generates, before your code runs.
How about do it in another PHP page, and you do a iframe include / redirect user to the second page?
I'm not sure the exact length of time between your transaction and your check; but it certainly seems that your session cookie has expired. Sessions expire usually after 45 minutes or so by default. This is to free up more uniqid's for php to use and prevent potential session hijacking.
I'm not sure if you have a custom session handler and whether it's stored in the database but guessing from your posts and comments on this page I would assume it is stored in server side cookies.
Now the solution to your problem, would be to bite the bullet and store the necessary data in the database and access it via the session id, even if it means creating another table to sit along side your orders table.
If however you are doing the action immediately then the other explanation is that either the user logged out or committed an action which destroyed their session (removing the server side cookie).
You will see these cookies in your servers /tmp folder, try have a look for your cookie, it should be named 'sess' + $session_id.

Categories