Solved

PHP login page takes several attempts in order to login?

Posted on 2008-10-31
11
252 Views
Last Modified: 2013-12-13
For some reason it takes many tries in order to login while using the right password and username so it has to be a mistake in code. Any ideas on how to fix that from happening?
<?php
session_start();
 
// connection to database excluded
 
$problem = FALSE;
if (isset ($_POST['submit'])) { // Check if submitted
	$problem = FALSE;
        // Username
        if (empty ($_POST['username'])) {
                $problem = TRUE;
                echo 'Please enter a username!<br/>';
        }
        elseif (empty ($_POST['password'])) {// Password
                $problem = TRUE;
                echo 'Please enter a password!<br/>';
        }
        else
        {    
                $username = mysql_real_escape_string($_POST['username']);
                $password = mysql_real_escape_string($_POST['password']);
                $query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'") or die( mysql_error() ); 
                // Validate Username and Password
                if (mysql_num_rows($query) == 1) { 
                        $_SESSION["username"] = $_POST["username"];
						$_SESSION["password"] = $_POST["password"];
                        $_SESSION["valid_time"] = time();
                        header ('Location: http://www.magnumdirectory.com/cPanel');
                        exit();
                }
                else
                {
                        $problem = TRUE;
                        echo 'Please enter a valid username and password.<br/>';
                }
        mysql_close(); // Close the database connection.
        }
} // end all
 
?>

Open in new window

0
Comment
Question by:magnumdirectory
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
11 Comments
 
LVL 12

Expert Comment

by:adrian_brooks
ID: 22855048
Try using this to ensure that you're not creating a new session when one is not needed.
Once you create a session, the session file is created and stored on the webserver for later recall.
So, you should only need to create a new session in the event that one is not detected  as already existing for this instance.
if(!session_id()) session_start();

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 22855220
There's nothing wrong with the login script. Most likely your session is being garbage collected too soon. What is the path to your sessions directory? What is session.gc_maxlifetime?
0
 

Author Comment

by:magnumdirectory
ID: 22855586
session.save_path = /var/php_sessions
session.gc_maxlifetime = 1440
0
Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

 
LVL 82

Expert Comment

by:hielo
ID: 22855617
The only thing that seems "odd" on the code you posted is that you are NOT checking if the user is already authenticated. If the user's session has not expired, then you should not be reauthenticating them. Simply redirect them and quit.

As of the info you provided, those are reasonable values. Out of curiousity, what do you get when you execute:
echo $_SERVER['DOCUMENT_ROOT'];
<?php
session_start();
$problem = FALSE;
//first check if the user is already authenticated
if( isset($_SESSION['username']) )
{
	//if so, redirect him/her immediately
	header("Location:  http://www.magnumdirectory.com/cPanel/");
 
	//and quit login.php right away
	exit;
}
// otherwise check if submitted data - attempting authentication
elseif ( isset ($_POST['submit']) )
{ 
	// Username
	if ( empty ($_POST['username']) )
	{
		$problem = TRUE;
		echo 'Please enter a username!<br/>';
	}
	// Password
	elseif (empty ($_POST['password']) )
	{
		$problem = TRUE;
		echo 'Please enter a password!<br/>';
	}
	else
	{
		// connection to database goes here
 
		$username = mysql_real_escape_string($_POST['username']);
		$password = mysql_real_escape_string($_POST['password']);
		$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'") or die( mysql_error() ); 
		// Validate Username and Password
		if (mysql_num_rows($query) == 1)
		{
			$_SESSION["username"] = $_POST["username"];
			$_SESSION["password"] = $_POST["password"];
			$_SESSION["valid_time"] = time();
			header ('Location: http://www.magnumdirectory.com/cPanel/');
			exit();
		}
		else
		{
			$problem = TRUE;
			echo 'Please enter a valid username and password.<br/>';
		}
		mysql_close(); // Close the database connection.
	}
} // end all
?>

Open in new window

0
 

Author Comment

by:magnumdirectory
ID: 22855667
When I use:
echo $_SERVER['DOCUMENT_ROOT'];

I get this: /home/users/web/b422/moo.myusername

I tested out the code and it does seem to work a lot smoother  but I think there is still a problem. I'm guessing it is the session_start(); because this is a seperate file from my login page but it is the post action of the form and the login page has session_start(); at top so would that be starting 2 sessions?
0
 
LVL 82

Accepted Solution

by:
hielo earned 500 total points
ID: 22855683
Assuming you have all these:
http://www.yoursite.com/page1.php
http://www.yoursite.com/page2.php
http://www.yoursite.com/page3.php

AND ALL of them need authentication, what you need to do is save the following as:
http://www.yoursite.com/checkAuthentication.php
<?php
session_start();
if( !isset($_SESSION['username']) || empty($_SESSION['username']) )
{
header("Location: http://www.yoursite.com/login.php");
exit;
}
 
Then each of page1.php,...,page3.php need to begin with this:
<?php
require_once( $_SERVER['DOCUMENT_ROOT'] ."/checkAuthentication.php" );
 
/* after these point, you do NOT need to call session start because the require_once statement above includes/imports "checkAthentication.php" AND it already calls session_start(); */
 
?>

Open in new window

0
 

Author Comment

by:magnumdirectory
ID: 22855752
Tried that and the pages I put it on just show nothing but white space:(
0
 
LVL 82

Expert Comment

by:hielo
ID: 22855759
look at your sessions directory. Is it empty? most likely the permissions are not right and the server is not able to write to it. If you do not have access to set the permissions on that folder contact the IT support from your host company.
0
 

Author Comment

by:magnumdirectory
ID: 22858263
Awesome I think I got it to work by backtracking a bit with what you provided. Seems to work pretty good now. Had to add a bit more control to the login page to see if they are logged in or not and that seems to have done the trick along with the checkAuthentication file! Thanks for all the help I really appreciate it:)
0
 

Author Closing Comment

by:magnumdirectory
ID: 31512232
This really did the trick for the most part! I had the sessions unconstrained which seemed to cause the problem but this is the cure to the problem:) Thank you!!!
0
 
LVL 82

Expert Comment

by:hielo
ID: 22858552
glad to help.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

690 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