Tessa
Tessa

Reputation: 163

PHP check and create cookie

I think I may be going mad. I'm trying to put a small piece of PHP code into my website that will check if there is a cookie. If not it will add an element to the page and load a cookie.

The code I have is:

<?PHP
if (!isset($_COOKIE['cookiename'])){
echo 'my html code';
setcookie('cookiename','cookievalue',time()+60*60*24*365,'/');
}
?>  

I came to this code by following tutorials and books but when I navigate to the page (after deleting cookies) the banner doesn't appear. I've placed the html code in the page directly without the PHP code and it appears fine.

Can anyone tell me what I'm doing wrong?

EDIT - I have changed the code so that the if statement is now looking for the cookie name (D'oh!) but it still isn't printing the banner to the website. I'm currently working on localhost, would that make a difference?

Upvotes: 0

Views: 47

Answers (1)

previous_developer
previous_developer

Reputation: 10988

You set cookiename but you check cookievalue in if statement.

This should work:

<?php
if(!isset($_COOKIE['cookiename'])) {
    echo 'my html code';
    setcookie('cookiename', 'cookievalue', time() + 60 * 60 * 24 * 365, '/');
}

Upvotes: 2

Related Questions