I have a login form with a remember me check box that sets the user email in a cookie that I then want to auto fill in the username the next time they log in. Also, when I use firbug it shows the path of the cookie in the directory where the login.php
page is. The index.php
is not in the same directory as the login.php
directory.
So I have index.php
page with the login form. When the user submits the form it calls login.php
which has this piece of code:
if (isset($_POST['email'])) {
if (isset($_POST['remember'])) {
setcookie("email", $_POST['email'], time() + 9999999);
$_COOKIE['email'] = $userEmail;
}
}
and then on the index.php
code I have this code:
$userEmail = $_COOKIE['email'];
and then I use the $userEmail
variable to autofill in the username field like this:
<div class="form-group <?php if(isset($userEmail)) { echo $addClass; }?>" >
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" value="<?php if(isset($userEmail)) { echo $userEmail; } ?>">
</div>
I can see that the cookie is being set, but when I try to echo the cookie (email address) it displays nothing.
I know that I am probably not doing this in the best way possible, but it used to work and now it stopped working. Any suggestions on what I am doing wrong?
EDIT: When I use Firebug I see this in the Cookies tab:
When I var_dump($_COOKIE['email'])
it show NULL
if (isset($_POST['email'])) {
if (isset($_POST['remember'])) {
setcookie("email", $_POST['email'], time() + 9999999);
$_COOKIE['email'] = $userEmail;
}
}
look at the line $_COOKIE['email'] = $userEmail;
this should be $userEmail = $_COOKIE['email'];
because at that point $userEmail
hasn't been given a value so you are essentially setting $_COOKIE['email']
to a null value.
either that or you need to set $_COOKIE['email'] = $_POST['email'];
I think :
if(isset($userEmail))
:
should be :
if(isset($userEmail) && !empty($userEmail) )
Thanks for all the answers, but this change has fixed the issue. It was setting the path of the cookie to the directory where the login.php
page was so I had to set the path of the cookie for all directories.
I changed this:
if (isset($_POST['email'])) {
if (isset($_POST['remember'])) {
setcookie("email", $_POST['email'], time() + 9999999);
$_COOKIE['email'] = $userEmail;
}
}
to this:
if (isset($_POST['email'])) {
if (isset($_POST['remember'])) {
$userEmail = $_POST['email'];
setcookie("email", $userEmail, time() + 9999999, "/");
}
}
I added "/"
to the setcookie