0

I've tried for 2 hours now to set cookie on my page and after reading on internet a lot, I still can't find out what i'm doing wrong. This is my code:

<?php

$cookie_name = "user";
$cookie_value = "MyUserName";

$days = 86400*30;
$cookie_time = $days+time();

setcookie($cookie_name, $cookie_value, $cookie_time, '/');

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

?>

The result of my Echo is "Cookie named 'user' is not set!" every time! Can somebody help me? :)

NickiJey
  • 29
  • 2
  • 7
  • 2
    `setcookie()` sets a cookie and returns `false` on error. You can't assert it doesn't work if you don't verify at least two things: 1) The return value 2) Whether the HTTP header shows up in the response – Álvaro González May 23 '16 at 12:02
  • 2
    BTW, your current verification is not correct. As [the manual](http://php.net/setcookie) says: "Once the cookies have been set, they can be accessed on the **next page load** with the $_COOKIE array". – Álvaro González May 23 '16 at 12:07
  • 1
    Another issue you might have would be the domain you are testing on.. if it's localhost you should follow this: http://php.net/manual/ro/function.setcookie.php#73107 – Mihai Matei May 23 '16 at 12:10
  • No, im using one.com – NickiJey May 23 '16 at 12:13

2 Answers2

2

your have syntax error in you code yo miss to colse the else statment

try this then your code will set the cookie

$cookie_name = "user";
$cookie_value = "MyUserName";

$days = 86400*30;
$cookie_time = $days+time();

setcookie($cookie_name, $cookie_value, $cookie_time, '/');

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];
}
Osama Jetawe
  • 2,697
  • 6
  • 24
  • 40
0

You forgot to close the else statement:

else
{
echo "Cookie '" . $cookie_name . "' is set <br/>";
echo "Value is: " . $_COOKIE[$cookie_name];

Tip: You should turn on Error Reporting by adding this code to the top of your PHP files which will assist you in finding errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
Panda
  • 6,955
  • 6
  • 40
  • 55