Beebarbo
Beebarbo

Reputation: 1

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!

Upvotes: 0

Views: 399

Answers (2)

Webeng
Webeng

Reputation: 7113

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]"

Upvotes: 1

Bartosz Zasada
Bartosz Zasada

Reputation: 3900

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.

Upvotes: 3

Related Questions