简体   繁体   中英

PHP setcookie / cookies not working

I pulled this file from w3schools, it works perfectly fine through their editor but when I upload it on my hosting service it keeps showing up as "Cookie 'user' is not set". I checked my php.ini file and it seems like cookies are turned on, are there other settings that might be causing this problem?

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), ""); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
 echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
 echo "Cookie '" . $cookie_name . "' is set!<br>";
 echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Thank you very much!

You have a line of HTML before your PHP code. I assume output buffering is off, so this line causes the response headers to be sent. Move the first line behind the PHP code.

You might not have cookies enabled on your browser. If you are using chrome, you can try the following steps:

  1. Click the menu icon on the browser toolbar.
  2. Select Settings.
  3. Click the Show advanced settings
  4. Click Content Settings
  5. In the "Cookies" section of the dialog that appears, make sure Allow local data to be set is selected to allow both first-party and third-party cookies.
  6. Click Close.

If you are using another browser, just google: "Allow coockies on [Browser Name] "

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