1

I need to display a message on my site using cookies.

I tried to use this code :

<?php 
if (isset($_COOKIE['visit']) && $_COOKIE['visit'] == "true"){
  echo 'cookie set, welcome back';
} else {
  echo 'cookie not set, welcome new user';
  setcookie("visit", "true", time()+60*60*24*600);
}
?>

I don't known how to do it, please help!

Alessandro
  • 900
  • 12
  • 23
Marius
  • 13
  • 2
  • You tried this code and...? Do you get an error? – Mickaël Leger Jun 25 '18 at 14:11
  • They look like *hokie cokies* to me... – CD001 Jun 25 '18 at 14:12
  • You can't `echo` before `setcookie()`; you *should* be getting a [Headers already sent](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) error. – CD001 Jun 25 '18 at 14:14
  • @CD001 it depends from server config – Yura Rosiak Jun 25 '18 at 14:16
  • @Marius check the extension of your php file – Yura Rosiak Jun 25 '18 at 14:17
  • @YuraRosiak not really, setting the cookie is part of the HTTP header - if you're echoing something out (without output buffering) you've closed the header... unless you're just referring to the error message not being displayed. In which case the error is still happening, it's just not telling you about it. – CD001 Jun 25 '18 at 14:19

2 Answers2

1

You need to run setcookie first to get it added to the header. When you run echo first, the header closes and you can't modify it anymore. This is mentioned in the docs of setcookie.

<?php 
if(isset($_COOKIE['visit']) && $_COOKIE['visit'] == "true"){
    echo 'cookie set, welcome back';
}else{
    setcookie("visit", "true", time()+60*60*24*600);
    echo 'cookie not set, welcome new user';
}
?>
swardu
  • 26
  • 4
-1

What message do you want to display? as the code is working perfectly

you can use the following code.

<?php
if(isset($_COOKIE['visit']==true){
  echo "Write here your message";
}
?>
Stephen
  • 69
  • 2
  • 10