简体   繁体   中英

PHP: Can't store to cookies

PHP newbie here, I can't understand what I'm doing wrong here. I'm trying to implement a cliché remember me function but I can't get the cookies to work. I've been at this for a good while.

All of this is wrapped in a password check function and I'm perfectly able to both login and echo my session. But I can't seem to set my cookie. I'm using MAMP.

if($_POST['_remember'] == 'true') {
    $cookie = $_SESSION['user']['id']. '-' .$_SESSION['user']['password']. '-' .$_SESSION['user']['timestamp'];
    setcookie('remedy', $cookie, time() +60*60*24*7, '/', 'localhosttest');
  } else {
    //destroy any previously set cookie
    setcookie('remedy', '', time() -60*60*24*7, '/', 'localhosttest');
  }

echo $_COOKIE['remedy'];

I really wish there was something else I could give you, but this is all I have. I'm a graphics designer and a photographer, this kind of logic isn't even near my ballpark. I apologise for the vague title, I'd fix it if I knew how to be more specific.

Also, my plan is to get the user ID, password (hashed and salted) and timestamp checked with the same values on the server. The timestamp value will be updated whenever the user browse the site. Is this good practice?

setcookie() prepares a cookie to be sent with the server response to the client. The $_COOKIE array is populated only when the Client sends a request.

After you setcookie(), check the $_COOKIE array on the next page the user requests--you'll see the cookie you created on the prior page request.

Note the 'on the next page load' from the documentation (http://php.net/manual/en/function.setcookie.php):

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.

你可以通过开放的crome控制台(F12) - >资源 - > cookies - > yourSite检查你的cookie是否存在。

Is your domain a fully qualified domain ? Domain names usually need to have a . (dot) in it to accept cookies.

For the answer about the cookie have a look at Rays answer.

I strongly recommend you to never store passwords on the client side because there are some security risks:

  • If you serve your pages with http, you always send your password unencrypted through the internet
  • Spyware or another user of the same computer could easy find out users credentials

You can't make it in a totaly secure way. I recommend you to store just a random hash inside the cookie, which is also stored in the database with user Credentials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM