Solved

PHP user login and automatic logout issues

Posted on 2013-06-27
13
2,383 Views
1 Endorsement
Last Modified: 2013-07-02
Hello,

I have a login page in PHP.  This works in that users can login however the error checking (wrong password doesn't work correctly).  If the user enters an invalid password then I still get a response "good" and the page gets redirected when I should be getting "invalid username or password" and reload login page.  I don't understand why the code doesn't return "bad" for wrong password/login.  Here is a snippet:

$rs1=$conn->execute($query1);
If($rs1){
	$status= "good";
	$teacherID = strval($rs1['UserID']);
	$teacher = strval($rs1['Teacher']);
	$avatar = strval($rs1['Avatar']);
	//if( empty($mysession)){
	//	$micro = microtime();
	//	$micro = str_replace(" ", "",$micro);
	//	$micro = str_replace(". ", "",$micro);
	//	$mysession = "teacher" . $micro;
	//}
	//session_name($mysession)
	session_start();
	$_SESSION['teacher'] = $teacherID;

} else {
	$status= "bad";
}

Open in new window


Also, I don't know how to put in place an automatic logout for the user after say 15 minutes of inactivity.......any pointers would be much appreciated.

Cheers,
1
Comment
Question by:1Cougar
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 39280495
Your if statement is wrong try using this one code:
if(mysql_num_rows($rs1)>0){
	$status= "good";
	$teacherID = strval($rs1['UserID']);
	$teacher = strval($rs1['Teacher']);
	$avatar = strval($rs1['Avatar']);
	session_start();
	$_SESSION['teacher'] = $teacherID;

} else {
	$status= "bad";
}
  

Open in new window

0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39280496
If the password checking doesn't work, then it's not really a 'login page', more of a 'pass-thru' page.  Here http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html is Ray's EE article on the subject.  Note that the default timeout for PHP sessions is 24 minutes but that is not a precise timeout.  It is rarely necessary to get any pickier than that.
0
 

Author Comment

by:1Cougar
ID: 39280525
@ jagadishdulal :

I am not using mysql but sql server....I tried your code but it still executes the "successful" login when there are no records from the query with an invalid password.

??
0
 

Author Comment

by:1Cougar
ID: 39280721
I have the login working now, but still need to understand the logout.....

On the php page to process login I have this code:
session_start();
	
	$_SESSION['loginTime'] = time();

Open in new window


and the user gets redirected to the site.  However, when I include this code the alert value is null....so I am guessing the session variable is not being saved:

var thistime = <?php echo "'".$_SESSION['loginTime']."'";?>;
	alert(thistime);

Open in new window


Does anyone know what I am doing wrong?

Many thanks again....
0
 

Author Comment

by:1Cougar
ID: 39280828
Hello,

This is my current situation....the user logs in and is directed to the main site (php page).  I have this code at the top of the page:

session_start();
		$inactive = 60;
		if(isset($_SESSION['loginTime'])) {
			$session_life = time() - $_SESSION['loginTime'];
			if($session_life > $inactive)
				{
					session_destroy(); 
					header("Location: http://www.infocuseurope.com/trainer/pages/IFETeacherlogin.php");
				}
		}
		
		$_SESSION['loginTime']= time();

Open in new window


However, the user never gets redirected after 60 seconds.....can anyone see what might be wrong with my logic?
0
 

Author Comment

by:1Cougar
ID: 39280833
I am looking for a solution for logout after inactivity....
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39281136
PHP already has a built-in solution for logout after inactivity.  All you need to do is embrace it!  Do not write separate programming to try to cause this to happen -- all that will happen is that you will get confused by the overlapping layers of your programming and the PHP session handler.

You may want to get some foundation in how PHP works.  There will be differences in MySQL and SQL Server, but SQL is SQL and the differences will be mostly a matter of query syntax, and not a matter of design principle.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

You will also want to understand why there is no such thing as a "logged in" user.  This is due to the stateless nature of the HTTP client-server protocol.  This article explains it.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

PHP sessions are not eliminated by session_destroy().  If you read the Login-Logout article, you will find a workable way to force a logout condition.  Here is a bit more about how the session handler works.  You must read and understand these links to work with sessions.
http://php.net/manual/en/book.session.php
http://php.net/manual/en/session.examples.basic.php

When the client requests a page that contains the session_start() statement, the following things take place:

1. PHP initiates the garbage collector.  It looks at all sessions on the server to see if there is any recent use of the session data.  If any session data anywhere has not been accessed in the last 24 minutes, PHP deletes that session data.  This has the effect of causing any client with 24 minutes of inactivity to be logged out.  Inactivity for this purpose is defined as the absence of any HTTP request.

2. PHP looks to see if a session cookie is associated with the request. If a cookie is found, PHP attempts to load the pre-existing session data into the $_SESSION array.  The data may be present or it may have been deleted by the garbage collector.  To the extent that the session data is found, it is loaded into the session array.  If no cookie is found, obviously no session data can be found, and no action occurs at this point.

3. PHP issues a setcookie() command with a pointer to a session storage area and an expiration time of zero seconds.  This has the effect of causing the cookie to expire when the browser is closed.*

When the script terminates, PHP writes the contents of $_SESSION to the session storage area that was designated by the session cookie.

That's it.  You can complicate things or mess this process up with various configuration settings, but if you don't actively do something to change the process, you can depend on this sequence of events to make your scripts work correctly.

1. Put session_start() at the logical top of your script.  Do this unconditionally on every page without exception, no excuses.

2. Add and remove data from the $_SESSION array.  Expect it to be present and persistent from request to request.

3. Expect the session data to be eliminated when the client closes the browser.*

4. Expect the session data to be eliminated when the client is inactive for 24 minutes.

It's just that simple, but it's important to understand the principles if you're using the session to authenticate a client for separate privileges, such as a "login" condition.  So please read the articles and links, then post back if you still have questions.
---
* The "developer-only" gotcha associated with closing the browser goes something like this.  You open a FF browser window and login as User-1.  Then you open another FF browser window and login as User-2.  Then you close that window, and navigate back to the original window expecting to find User-1.  But, gadzooks, you find User-2!  This never bothers normal users, because they sign into the site using their own credentials and never try to be "two users at once."  It often drives developers nuts because many novice developers do not understand that all instances of the same browser share the same cookie jar.  This is true whether the browsers are in the same window or separate windows.  FF does not share with IE or Chrome, etc, but all of the same browsers share their common jar.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39281874
Glad you asked this question!  Here is the article that resulted from researching the answer.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html

Best to all, ~Ray
0
 

Author Comment

by:1Cougar
ID: 39289479
@Ray_Paseur,

Thank you--this has been very helpful and I have have implemented much of what you suggested.

However, I am still not achieving what I really would like, which is a logout after 10-15 minutes and a redirect to the login page.  

The user logins to a main page.  On the main page are several tabs which load other pages, but via AJAX -so there is not another request sent for the main page.  So you would think that after 24 default minutes of inactivity at the most the page should be redirected to the login page if the user tries to come back and change data.  But, this is not what is occurring.  The main page always stays and looks to the user like they can enter data.

I have put this code in the main page:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
	header("Location: http://www.mysite.com/trainer/pages/MyLogin.php");
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Open in new window


And if I hit "refresh" after 2 min (set for testing) then it does send me to login page.  But, if I don't refresh and instead just want to continue and enter data (you might recall I am doing a scheduling app) then it will allow me.  Except I am still experiencing some strange behavior with data getting deleted for some users when they "save" so I would like to force a log out to rule out the possibility that the data corruption/deletion is coming from expired data cache with a page that remains so the user thinks they can still perform operations.

Since I have "tabs" on the main page, maybe just having this script on the main page isn't good enough but I tried to add it to the php pages that get loaded in the tabs, it threw an error, and this also did not work in that I never got logged out and sent to the login screen automatically after 2 minutes of inactivity.

I hope I am making sense....any thoughts would be much appreciated.

Thanks again,
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39289943
I think you're still swimming upstream on this problem.  To fully understand what is happening you need to delve into the behavior of the HTTP Client/Server protocol.  Please read this.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

In the client-server protocol, there is no such thing as a server-initiated activity.  The concept that the client computer would "get redirected" to the login page seems like a nice idea but it can only happen after the client has made a request to the server and the server makes a response.

If the human client is doing nothing - just watching the screen - the server will not receive any communication and will not be able to make any response.  Unless (and this is a big unless) the non-human client (computer, handheld, phone, etc) is able to make an AJAX request to the server.  The AJAX request can be triggered by a number of things, including a timer running on the client computer.

If the human client is doing something like entering data into a plain old HTML form, the client machine is not making any requests to the server, so the appearance of events as seen by the session handler is the same as an idle client.  You might be able to get around this by having an onKeyUp event that signaled the server via an AJAX request.  The server could renew its timeout period each time the event was signaled.

You might also think about the overall design of the data entry process.  The central goal, it would seem to me, would be to avoid losing the data and forcing the client to start over.  This would suggest an onBlur event that sent each field to the server via an AJAX request as soon as the (human) client moved her attention away from the input control.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39290634
Ray is right.  The server just reacts to requests from the client.  Web sites like Facebook that appear to act differently are doing frequent AJAX requests to the server, the server is not initiating anything.
1
 

Author Comment

by:1Cougar
ID: 39293469
My page uses AJAX not page reloads and I understand what you are saying.  I am adding some code to the AJAX requests to check for timeout.

Thanks a lot,
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39293491
Thanks for the points - it's a really good question! ~Ray
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now