1

Alright so what I am doing is I have a Text box and submit button that posts to the current page. The user can put their name in it. It creates a cookie and that cookie will echo out their name on the page after they pressed submit.

But I can't seem to do this in one page refresh.

Here is what I have so far:

<?php 
error_reporting(E_ALL ^ E_NOTICE);
?>

<form action="#" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php 
$post = $_POST["fname"]; 

$expire=time()+60*60*24*30;
setcookie("user", $post, $expire);

echo $_COOKIE["user"];
?>

Thanks!

2
  • Can you post all the code instead you are using? – Perry Jun 16 '13 at 12:06
  • Updated it with all the code. – David Torner Jun 16 '13 at 12:08
2

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS array:

<?php
   if (isset($_POST['fname'])) {
       $post = $_POST["fname"]; 

       $expire=time()+60*60*24*30;
       setcookie("user", $post, $expire);
      header("Location: index.php"); //notice the redirect?
    }
 ?>

<form action="" method="post">
   Name: <input type="text" name="fname">
   <input type="submit">
</form>

<?php if (isset($_COOKIE['user'])) {
   echo $_COOKIE["user"];
  }
?>
2
  • 1
    Don't use $HTTP_COOKIE_VARS because this is deprecated. In you example you use $_COOKIE wat is correct. – Perry Jun 16 '13 at 12:58
  • @DavidTorner glad to help you :) – Khawer Zeshan Jun 16 '13 at 16:09
1

cookie should be set before outputting any content (html)

<?php 
error_reporting(E_ALL ^ E_NOTICE);

if(isset($_POST['fname'){
    $post = $_POST["fname"]; 

    $expire=time()+60*60*24*30;
    setcookie("user", $post, $expire);

    echo $_COOKIE["user"];
}
?>
<form action="#" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
1
  • How come this answer is accepted? You cannot SET and ECHO cookie without page refresh – Khawer Zeshan Jun 16 '13 at 12:32
1

Try this code I also add some checks:

<?php 
error_reporting(E_ALL ^ E_NOTICE);

if ($_SERVER['REQUEST_METHOD'] === 'post' && isset($_POST['fname']) && !empty($_POST['fname'])) {
$post = $_POST["fname"]; 

$expire=time()+60*60*24*30;
setcookie("user", $post, $expire);
}
?>

<form action="#" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php if (isset($_COOKIE['user'])) {
echo $_COOKIE["user"];
} else {
echo 'There is no firstname.';
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.