Tchiggy
Tchiggy

Reputation: 131

Unable to read cookies in PHP

I'm learning PHP and I recently got stuck at trying to learn cookies. In other words, I did exactly the same as the guy in tutorial, but I somehow can't echo the cookies in if(isset()) condition. But when I click on the Cookies in use in chrome, I can clearly see the cookie has been saved.

My code:

<?php
$name = "Jozef";
$age = 100;
$duration = time() + (60*60*24*7);
setcookie($name, $age, $duration, '/');

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trying cookies</title>
</head>
<body>
    <?php 
        if(!empty($_COOKIE['name'])){
            $newName = $_COOKIE['name'];
            echo $newName;
        }
        else{
            echo "<br>nope";
        }
    ?>
</body>
</html>

In the picture below, you can see on the left side, that the first condition didn't run, but the second did.

Picture showing that the cookie is already in use

Upvotes: 0

Views: 65

Answers (3)

samy rwt
samy rwt

Reputation: 11

Cookie Syntex

setcookie(name, value, expire, path, domain, secure, httponly);

try this one

<?php
$name = "user";
$value = "Samy_tech";
$duration = time() + (86400 * 30);
setcookie($name, $value, $duration, "/");

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

Output

Cookie 'user' is set!
Value is: Samy_tech

Note: by this code you can properly create your cookie and read it.

Upvotes: 0

Romi Halasz
Romi Halasz

Reputation: 2009

You need to set the name of the cookie, not just the value:

setcookie('name', $name, $duration, '/');

In your second image you have a cookie named 'Jozef'. I assume you wanted to have a 'name' cookie with the value 'Jozef'. Right?

Only then will $_COOKIE['name'] be defined.

Hope this helps.

Update:

You should set the name and age separately:

setcookie('name', $name, $duration, '/');
setcookie('age', $age, $duration, '/');

Upvotes: 1

Jatin Kaklotar
Jatin Kaklotar

Reputation: 505

You have wrongly implement , take a look of below example

<?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>

Upvotes: 1

Related Questions