title: Auto-login with cookies
body: <p>I've been trying to make an auto-login feature for my login script for 2 nights now.</p>
  
  <p>I have a field in my users table called <code>session_key</code> varchar(255) in which I store the users IP address hashed with MD5.</p>
  
  <p>If the cookie is set, session variables will be set and if not a form will appear.</p>
  
  <p>When they login and if they have checked a checkbox named <code>autologin</code> it will store their MD5 hashed IP address in field <code>session_key</code>.</p>
  
  <p>Now if they close their browser and come back, I check that their cookie is equal to session_key in the database.</p>
  
  <p><br><br>
  This is the messy code! I didn't think it would be this hard to implement an auto-login function...</p>
  
  <pre><code>session_start();
  
  // see if the auto-login cookie exists, if so set sessions vars
  if (isset($_COOKIE['autologin'])) {
  $user=mysql_query("select * from users where session_key = $_COOKIE[autologin]");
  $row3=mysql_fetch_assoc($user);
  
  
  
          if ($_COOKIE['autologin'] == $row3['session_key']) {
  
             $_SESSION['id'] = $row3['id'];
             header("Location: login.php");
          }
      }
  
  
  // User pressed "Login"
  if (count($_POST)) {
  
  $result = mysql_query("SELECT id FROM users 
                         WHERE username = '".mysql_real_escape_string($_POST['username'])."' 
                         AND password = '".mysql_real_escape_string($_POST['password'])."' ");
  
  
  if (mysql_num_rows($result) == 0) {
          $error = '&lt;script&gt;alert("Wrong username and/or password.\nTry again.")    &lt;/script&gt;';
  } else {
      $_SESSION['id'] = mysql_result($result, 0, 'id');
      header("Location: login.php");
      mysql_query("UPDATE users SET session_key = '".md5($_SERVER['REMOTE_ADDR'])."'");
      setcookie("autologin", md5($_SERVER['REMOTE_ADDR']), time()+3600);
  }
  
  }
  
  
  
  if (isset($_SESSION['id'])) {
  
  exit('You are logged in!');
  
  }
  
  
  
  &lt;form method="post"&gt;
  
  &lt;tr&gt;
  &lt;td valign="top" width="95px"&gt;&lt;b&gt;Username:&lt;/b&gt;&lt;/td&gt;
  &lt;td&gt;&lt;input type="text" name="username" size="22" /&gt;&lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
  &lt;td valign="top"&gt;&lt;b&gt;Password:&lt;/b&gt;&lt;/td&gt;
  &lt;td&gt;&lt;input type="password" name="password" size="22" /&gt;&lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
  &lt;td valign="top"&gt;&lt;b&gt;Auto-login:&lt;/b&gt;&lt;/td&gt;
  &lt;td&gt;&lt;input type="checkbox" name="autologin" /&gt;&lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
  &lt;td&gt;&amp;nbsp;&lt;/td&gt;
  &lt;td&gt;&lt;input type="submit" value="Login" /&gt;&lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;/form&gt;
  </code></pre>
  
  <p>Is this even safe? Is it easy to manipulate cookies? </p>
  
  <p>Afaik, youtube sports this function - how do they do it?</p>
  
  <p>I can't get this to work, can someone help me?</p>