-1

The code below is a simple experiment.Here i am trying to create a name input form which will be set as a cookie in the browser.But it appears that it is not working at all.Where might be the problem here.I am a beginner in php.So,it would be great if someone point out the mistakes i have made

<?php
if(isset($_POST['name']) && !empty($_POST['name'])){
$cookie_value=$_POST['name'];
setcookie('user',$cookie_value, time() + 3600, '/');
}
?>
<html>
<body>

<?php
if(isset($cookie_value)&& !empty($cookie_value)) {
    echo "user is".$cookie_value;
} else {
    echo "Cookies are not set";
}
?>
<form action=<?php echo $_SERVER['PHP_SELF'] ?> method='post'>
<input type='text' name='text'>
<input type='submit' value='submit'>
</form>

</body>
</html>
AL-zami
  • 8,902
  • 15
  • 71
  • 130

2 Answers2

1

You're calling $_POST['name'] but your inputs name is text. May want to change the variable to $_POST['text'].

castis
  • 8,154
  • 4
  • 41
  • 63
  • thanks!! browser didn't warn me for this.how can i get an error message for this types of error?? – AL-zami Feb 10 '15 at 15:45
  • You can get common php errors by adding `error_reporting(E_ALL); ini_set('display_errors', 1);` to the beginning of the file. – castis Feb 10 '15 at 15:46
  • *"how can i get an error message for this types of error??"* @al-Zami Are you not reading the comments under your question? Posted nearly 5 mins. before this comment? and 4 mins. after your initial question. – Funk Forty Niner Feb 10 '15 at 15:47
  • @Fred-ii- i put your error handling code at the front of my first php tag.Didn't work when i changed the input name attribute – AL-zami Feb 10 '15 at 15:49
  • 1
    @al-Zami If you changed the input name attribute, you won't be getting an Undefined index for it now, will we? ;-) – Funk Forty Niner Feb 10 '15 at 15:49
  • i've set an invalid name inside $_POST[] .didn't work either !! – AL-zami Feb 10 '15 at 15:56
0

After setting cookie and redirecting to another page (cookie will be visible after first redirect) you can access that cookie using $_COOKIE['user'].

I can't see that in your code and I'm pretty sure that's the reason.

And next problem is wrong input name, just like @castis pointed out.

Elon Than
  • 9,603
  • 4
  • 27
  • 37