Jump to content

php/mysql auto logout after 2 hour and reset password


jarvis

Recommended Posts

Hi all,

 

This I hope will make sense. I've the following code which when a user logins in, creates a session:


if (isset($_POST['submitted'])) { // Check if the form has been submitted. 

   require_once ('mysql_connect.php'); // Connect to the database. 

   // Validate the email address.    
   if (!empty($_POST['email'])) { 
      $e = escape_data($_POST['email']); 
   } else { 
      echo '<p class="error">You forgot to enter your email address!</p>'; 
      $e = FALSE; 
   } 
    
   // Validate the password. 
   if (!empty($_POST['pass'])) { 
      $p = escape_data($_POST['pass']); 
   } else { 
      $p = FALSE; 
      echo '<p class="error">You forgot to enter your password!</p>'; 
   } 
    
   if ($e && $p) { // If everything's OK. 
    
      // Query the database. 
      $query = "SELECT user_id, first_name, account_id FROM users WHERE (email='$e' AND pass=SHA('$p')) AND active IS NULL";    
      $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); 
          
         if (@mysql_num_rows($result) == 1) { // A match was made. 

         // Register the values & redirect. 
         $row = mysql_fetch_array ($result, MYSQL_NUM); 
         mysql_free_result($result); 
         mysql_close(); // Close the database connection. 
         $_SESSION['user_id'] = $row[0]; 
         $_SESSION['first_name'] = $row[1]; 
         $_SESSION['account_id'] = $row[2]; 

         // Start defining the URL. 
         $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); 
         // Check for a trailing slash. 
         if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { 
            $url = substr ($url, 0, -1); // Chop off the slash. 
         } 

         // Add the page. 
         $url .= '/index.php'; 

         ob_end_clean(); // Delete the buffer.    
         header("Location: $url"); 
         exit(); // Quit the script. 

      } else { // No match was made. 
         echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; 
      } 
       
   } else { // If everything wasn't OK. 
      echo '<p class="error">Please try again.</p>';       
   } 
    
   mysql_close(); // Close the database connection. 

} // End of SUBMIT conditional. 
?> 

<h1>Login</h1> 
<p class="maintext">Your browser must allow cookies in order to log in.</p> 
<form action="login.php" method="post"> 
   <fieldset> 
   <p class="maintext"><b>Email Address:</b> <input type="text" name="email" size="20" maxlength="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /></p> 
   <p class="maintext"><b>Password:</b> <input type="password" name="pass" size="20" maxlength="20" /></p> 
   <div align="center"><input type="submit" name="submit" value="Login" /></div> 
   <input type="hidden" name="submitted" value="TRUE" /> 
   </fieldset> 
</form> 

 

Each page I want protected then has this at the top


// If no first_name variable exists, redirect the user. 
if (!isset($_SESSION['first_name'])) { 

   // Start defining the URL. 
   $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); 
   // Check for a trailing slash. 
   if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { 
      $url = substr ($url, 0, -1); // Chop off the slash. 
   } 
   // Add the page. 
   $url .= '/index.php'; 
    
   ob_end_clean(); // Delete the buffer. 
   header("Location: $url"); 
   exit(); // Quit the script. 
    
} else { 
### page ### 
} 

 

What I'd like to do is set the session to automatically expire after 2 hours and the users password to reset to something different to prevent login.

 

I assume this is possible but where do I start?

Link to comment
Share on other sites

don't have a perfect solution, but you can change the lifetime of sessions in php.ini ... set `session.gc_maxlifetime` to 7200 (2 hours in seconds)

 

but to call some php code when that happens, may require a background script .. checking for expired login sessions periodically...

Link to comment
Share on other sites

Three way to do this

 

 

you can change the lifetime of sessions in php.ini ... set `session.gc_maxlifetime` to 7200 (2 hours in seconds)

#1 You can use cookies instead.  With cookies you can set the lifetime of that particular cookie instead of changing your permanent PHP settings

 

#2 You can store the page load/execution time in the SESSION...... you know... every page load that happens.  Just overwrite it.. over and over.. comparing it all the while with the current time.

 

#3 Create a table of actions in a database and check it everytime the page is loaded.  Pretty much the same thing as the session except you'll have records to keep of everything.

Link to comment
Share on other sites

Hi,

 

this is a simple thing I used.

 

If the user is inactive 10 mins I will log him out.

 

<?php
$_session['timein']=time();


$maxTime = 600; // this is 10 mins in secs.

$tot_time = time() - $_session['timein'];


if($tot_time > $maxTime)
{ session_destroy(); header("Location: logout.php"); }


?>

 

I check this on every page.

 

This might now be the exact code but I've just put whatever is on my mind.

 

hope it makes sense.

 

Cheers

Link to comment
Share on other sites

$_session['timein']=time();

$maxTime = 600; // this is 10 mins in secs.

$tot_time = time() - $_session['timein'];

if($tot_time > $maxTime)
{ session_destroy(); header("Location: logout.php"); }

?>

 

This won't work but it's the write idea.  It won't work b/c $tot_time will always be 0 therefore $tot_time will always be less than $maxTime... in turn NEVER destroying the session.

 

Something more along the lines of


$_SESSION['timeIn'] = (isset($_SESSION['timeIn'])) ?
(((time() - $_SESSION['timeIn'])

Link to comment
Share on other sites

Thanks GiriJ, that's more what I'm after. Would that be a session of 10 mins overall or per page if they remain on one page?

 

Do I add that on each page?

 

If this is an overall 10 mins, this is perfect as I can increase it to 2 hours. How could I then add in my pw reset?

 

This is my code to create a random pw

	// Create a new, random password.
	$p = substr ( md5(uniqid(rand(),1)), 3, 10);

	// Make the query.
	$query = "UPDATE users SET pass=SHA('$p') WHERE user_id=$uid";		
	$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
	if (mysql_affected_rows() == 1) { // If it ran OK.

		// Send an email.
		$body = "Your password to log into domain.co.uk has been temporarily changed to '$p'. Please log in using this password and your username. At that time you may change your password to something more familiar.";
		mail ($_POST['email'], 'Your temporary password.', $body, 'From: admin@domain.co.uk');
		echo '<h3>Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the "Change Password" link.</h3>';
		mysql_close(); // Close the database connection.
		include ('./includes/footer.html'); // Include the HTML footer.
		exit();				

	}

I can pull the username from the session I guess?

 

Thanks again!

Link to comment
Share on other sites

Hi all,

 

OK, I've found this code which works well to time out a session without inactivity

session_start();

//set timeout period in seconds
$inactive = 30; 
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {	
$session_life = time() - $_SESSION['timeout'];	
	if($session_life > $inactive) { 
		session_destroy(); 
		header("Location: logout.php");
	}
}
$_SESSION['timeout'] = time();


 

How can I set it to auto expire after a set time? i've tried

ini_set('session.gc_maxlifetime', 15); 

but that doesn't work. I placed that at the top of all pages. Any help is much apprciated!

Link to comment
Share on other sites

Sorry to bring this one back up but I'm still having issues.

 

In a nutshell, I need to kill my session, without the need of a page refresh after a set time period. It's not after inactivity, the site can be in use by someone but after say 2 hours will just end.

 

Upon killing the session, I need to run a php script.

 

is this possible?

do i need to add the code to each page or just to my header?

 

please see above for how I set up my session and the code used.

 

thanks in advanced!

Link to comment
Share on other sites

The only sure way of preventing access or the use of any specific 'temporary' password after a specific time has passed is to store the time value you want to test for in a database (flat-file, mysql...) on the server. The suggestions to store time values in a session variable can be easily bypassed by simply dropping the session id and logging in again.

 

If you want a specific password to only allow access for a specific time period, store the date/time when it was created (or first used) in a database table. Then on each page access check if the date/time for that password is farther in the past than a value of your choice. If it is, prevent access and take any other action that you need.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.