Solved

PHP login page takes several attempts in order to login?

Posted on 2008-10-31
11
248 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
  • 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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.

920 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

18 Experts available now in Live!

Get 1:1 Help Now