Reputation: 43
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!
Upvotes: 1
Views: 3922
Reputation: 9646
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"];
}
?>
Upvotes: 2
Reputation: 11700
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.';
}
?>
Upvotes: 1
Reputation: 3423
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>
Upvotes: 1