Solved

PHP login page takes several attempts in order to login?

Posted on 2008-10-31
11
247 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
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 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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
htacces issue 2 41
whm high memory usage in processes 7 38
php image upload 3 27
Wordpress Body Class 5 13
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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…

747 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

13 Experts available now in Live!

Get 1:1 Help Now