Jordi
Jordi

Reputation: 63

PHP: if(isset($_COOKIE['name'])) not working

I made an input form when the user types in a name. a isset($_COOKIE) checks if the made cookie already exists. if the cookie exists you'll get a message: Welcome back. if not you'll get the message: this is your first time here. but somehow i always get the message welcome back.

Here is my code:

<?php 
 if(!empty($_POST)) 
 {
    header("Location:form_data.php");
    setcookie('name',$_POST['name'], time() + (86400 * 30));
 }
 if(isset($_COOKIE['name']))
 {
   echo "Welcome back ".$_COOKIE['name'];
 }else
 {
    echo "hello ".$_COOKIE['name']; echo " this is your first time here.";
    setcookie('name',$_POST['name'], time() + (86400 * 30));
 }

?>

can someone help me with this problem?

Upvotes: 0

Views: 2912

Answers (2)

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

setcookie() must be called before any output is sent to the browser. Otherwise it will cause an header error.

In your code:

Change from:

 echo "hello ".$_POST['name']; echo " this is your first time here.";
 setcookie('name',$_COOKIE['name'], time() + (86400 * 30));

To:

  setcookie('name',$_POST['name'], time() + (86400 * 30));
  echo "hello ".$_POST['name']; echo " this is your first time here.";

So no other code will be executed after header() redirection, you should append exit() to it:

So also change:

header("Location:form_data.php");
setcookie('name',$_POST['name'], time() + (86400 * 30));

To:

setcookie('name',$_POST['name'], time() + (86400 * 30));
header("Location:form_data.php"); exit();

Upvotes: 3

Dario Eberhard
Dario Eberhard

Reputation: 74

Your code seems to be correct. (except the section pointed out by Karlo)

  1. Make sure you don't POST anything. Otherwise your cookie is already set.
  2. Make sure you delete your cookie from your browser.
  3. Make sure you refresh the page without sending the POST data again. So you should reach the "this is your first time" section.

Upvotes: 0

Related Questions