开发者

My cookies won't stay (PHP)

开发者 https://www.devze.com 2022-12-29 06:43 出处:网络
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!

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)

$use开发者_如何学运维rID 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消