Page 1 of 1

Autofill username and password field

Posted: Thu Jan 07, 2010 11:48 am
by Parmenion
I want to have a tick box on a log in system so when a user ticks it they are remembered on future visits. I've got it working through a cookie but I have run into one issue. When no cookie is set to start with the page displays an error stating the cookie doesn't exist. How can I get it to autofill the username and password fields only if the box has been ticked?

Here's the code for the tick box and cookie:

Code: Select all

 
if (!empty($_POST['remember']));
{
setcookie("user", $userid, time()+3600);
setcookie("password", $password, time()+3600);
}
 

Code: Select all

 
echo '<tr><td>Username:</td>';
echo '<td><input type="text" name="userid" value='.$_COOKIE["user"].'></td></tr>';
echo '<tr><td>Password:</td>';
echo '<td><input type="password" name="password" value='.$_COOKIE["password"].'></td></tr>';
 
I know I need something in the second piece of code to only set the value if the cookie is set but I'm not sure how to do this.

Any ideas?

Thanks

Re: Autofill username and password field

Posted: Thu Jan 07, 2010 12:38 pm
by AbraCadaver
Use the same logic as you did in the first part of your code (one way):

Code: Select all

$user = $pass = '';
 
if(isset($_COOKIE["user"])) {
   $user = $_COOKIE["user"];
}
if(isset($_COOKIE["password"])) {
   $pass = $_COOKIE["password"];
}
echo '<tr><td>Username:</td>';
echo '<td><input type="text" name="userid" value='.$user.'></td></tr>';
echo '<tr><td>Password:</td>';
echo '<td><input type="password" name="password" value='.$pass.'></td></tr>';
But I really wouldn't save the user's password in the cookie. This is very insecure! If $_COOKIE['user'] is set, then you should probably query the db for the user's pass when they hit the login page. Better yet, just save the user_id in the cookie and then query for the name and pass when needed. If this won't work for you then maybe save these values in session vars.

Re: Autofill username and password field

Posted: Thu Jan 07, 2010 8:15 pm
by Parmenion
Thank you very much, AbraCadaver, I have have got it working from your code with a few adjustments. I'm fairly new to PHP so sometimes miss simple things like that.

I've set up a database so that when a user logs in it connects and checks the username and password are correct. I heard cookies can be used to autofill the fields but really just wanted to get it to work first before looking at security issues. I feel pleased just to see it work. :)

I'll see if I can do what you've suggested next.