You should take your username, IP address and some hash (as the zombat suggested), encrypt it all (possibly using Base64) and save the resulting string as your cookie. Thus, someone cannot cheat or steal a cookie, because even if they did, the decrypted IP address would not match the IP address from which the request came. It is also better to use whitelists instead of dropping user input into the request.
So you get something like:
//First see if the auto-login cookie exists and is valid: if($_COOKIE['autologin']) { $users_query = "SELECT username FROM users WHERE last_login < SUBDATE(CURDATE(),30)"; $users_results = mysql_query($users_query); while($row = mysql_fetch_assoc($users_result)) { $users = $row['username']; } $auto_cookie = $_COOKIE['autologin']; $user_creds = explode("//", base64_decode($auto_cookie)); $user_name = $user_creds[0]; $user_IP = $user_creds[1]; $user_hash = $user_creds[2]; $username_check = (in_array($user_name, $users) ? true : false; $userIP_check = ($user_IP = $_SERVER['REMOTE_ADDR']) ? true :false; $so_far_so_good = ($username_check && $userIP_check) ? true : false; if($so_far_so_good) { $hash_query = "SELECT hash FROM userhash WHERE username = '$user_name'"; $hash_results = mysql_query($hash_query); $all_clear = ($user_hash == mysql_result($hash_results,0)) ? true : false; } } //Checks Login Data: if($_POST) { $users_query = "SELECT username FROM users"; $users_results = mysql_query($users_query); while($row = mysql_fetch_assoc($users_result)) { $users = $row['username']; } $username_check = (in_array($user_name, $users) ? true : false; $password_check = password_check(); // I do not feel comfortable enough with encryption and authentication to suggest // a method here. Suffice to say, you should have a strong password check system. $all_clear = ($username_check && $password_check) ? true : false; // You should only throw a log in error when they have attempted a login. Do not // give hints at your authentication methods in auto-login section. $set_cookie = ($all_clear && $_POST['set-auto']) ? true : false; if($set_cookie) { $new_hash = hash_maker(); // Again, look to the others for best hashing technique. $raw_cookie_data = $user_name . "//" . $_SERVER['REMOTE_ADDR'] . "//" . $new_hash; $enc_cookie_data = base64_encode($raw_cookie_data); setcookie("autologin", $enc_cookie_data, time()+3600); } } if($all_clear) { echo "Welcome Back!"; } else { //print login form here... }
source share