title: automatic logout after x minutes activity
body: <p>I have php scripts that confirm the password and username of a customer matches those that are stored in a database (username and password are stored in a users database). Once they login they will be redirected to their own page, but after a period of minutes inactivity I want them to be logged out, or redirected to the login.php. Can anyone help with a tried and tested method? Thank you in advance.</p>
  
  <pre><code>&lt;?php
  session_start();
  
  $username = mysql_real_escape_string($_POST['username']);
  $password = mysql_real_escape_string($_POST['password']);
  
  mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
  mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
  $query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
  $exists = mysql_num_rows($query); //Checks if username exists
  $table_users = "";
  $table_password = "";
  if($exists &gt; 0) //IF there are no returning rows or no existing username
  {
  
      while($row = mysql_fetch_assoc($query)) //display all rows from query
  {
      $table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
      $table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
      $table_id = $row['id'];
      $page_id = $row['page'];
  }
  if(($username == $table_users) &amp;&amp; ($password == $table_password)) // checks if there are any matching fields
  {
          if($password == $table_password)
          {
              $_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
              //echo $table_id;
              //echo $page_id;
  
              redirect ($page_id); //take the user to the page specified in the users table
  
          }
      else
      {
          echo "Login Failed";
      }
  
  }
      else
      {
          Print '&lt;script&gt;alert("1. Incorrect Password!");&lt;/script&gt;'; //Prompts the user
          Print '&lt;script&gt;window.location.assign("login.php");&lt;/script&gt;'; // redirects to login.php
      }
  }
  else
  {
      Print '&lt;script&gt;alert("Incorrect Username!");&lt;/script&gt;'; //Prompts the user
      Print '&lt;script&gt;window.location.assign("login.php");&lt;/script&gt;'; // redirects to login.php
  }
  function redirect($page_id)
  {
  /* Redirect browser */
  header('Location: home.php');
  /* Make sure that code below does not get executed when we redirect. */
  exit;
  }
  ?&gt;
  </code></pre>