0

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?

2
  • 1
    cookievalue and cookiename mmm two different things. Commented Sep 16, 2015 at 21:15
  • make sure that you are doing this before any output is done (no echo, <?php is in the beginning of the file, etc) Commented Sep 16, 2015 at 21:52

1 Answer 1

2

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, '/');
}
Sign up to request clarification or add additional context in comments.

2 Comments

D'oh! I knew it would be something stupid. It's obviously too late to be coding stuff! Thank you :-)
Hmm... looks like I spoke too soon. I've changed my code as suggested but the banner still doesn't appear :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.