Reputation: 335
Trying to learn cookies in PHP to me everything seems fine but it doesnt even set the cookie
here is the code
<?php
if (isset($_COOKIE['user'])) {
header('Location: simple.php');
} else {
if (isset($_POST['submit'])) {
if (isset($_POST['username']) && isset($_POST['password'])) {
if (isset($_POST['checkbox'])) {
$expire = time() + 60 * 60;
setcookie('user', $_POST['username'], $expire);
} else {
header('Location: simple.php');
}
} else {
echo 'Please Enter Your Information !';
}
} else {
echo 'Please Submit';
}
}
?>
tried
<?php
setcookie("testcookie","testvalue",0);
echo $_COOKIE['testcookie'];
?>
Result is
Notice: Undefined index: testcookie in /var/www/php-practice/cookies/test.php on line 1
and it sets the cookie testcookie
in browser with the value testvalue
Feel there is some error in $_POST['submit']
because
if (isset($_POST['submit'])) {
//everything else
} else {
echo 'Submit Button Problem !';
}
it prints the Submit Button Problem !
here is the HTML of the submit button
<input type="submit" value="Submit" name="submit" />
Looked at this question and tried it but still nothing
I tried everything I could but it doesnt work
Help !
Upvotes: 0
Views: 199
Reputation: 592
Note you can't set and display cookies on same page at same time. If you set and redirect to another page or reload the page, it will show the cookie value.
<?php
setcookie("testcookie","testvalue",0); //this will work
echo $_COOKIE['testcookie']; // won't work unless reloaded
?>
For your initial script. Ensure that $_POST['checkbox'] exists, is checkbox the name of your html form checkbox input?
//Your HTML form should include this
<input type="checkbox" value="1" name="checkbox" />
if (isset($_POST['checkbox'])) {
$expire = time() + 60 * 60;
setcookie('user', $_POST['username'], $expire);
} else {
header('Location: simple.php');
}
Edit your HTML Form to include method="post"
<form method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="checkbox" value="1" name="checkbox" />
<input type="submit" value="Submit" name="submit" />
</form>
Upvotes: 1