简体   繁体   中英

Unable to read cookie in php on localhost

PHP not reading cookie although I can see in browser.

//i set cookie in localhost/site/classes/php/user
setcookie("liu", $result[0]['user_id'], time() + 60 * 60 * 24 * 30, "/");
//trying to access it in localhost/site/index.php
$loggedInUser = $_COOKIE['liu'];

If you're running on localhost, you should explicitly set the cookie domain to false .

You could try:

setcookie("liu", $result[0]['user_id'], time() + 60 * 60 * 24 * 30, "/", false);

Have a further look here: Cookies on localhost with explicit domain

You cannot read a cookie you have set in the code above.

Cookies are sent with the headers to the browser.

PHP will be able to read the cookie only after the user navigates to the next page or you redirect him to a new page.

PHP will be able to read the cookie then because the browser will send it back via headers.

Read this: http://uk1.php.net/manual/en/function.setcookie.php

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);

We verify that we are not working in local, if we are in local we put the value of false in the variable $domain. If not, we pass the domain where the web is hosted.

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie( 'liu', $result[0]['user_id'], time() + 60 * 60 * 24 * 30, '/', $domain );

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