Custom Login Page not working

I have created a custom PHP/MySQL login page for a website I am working on. For some reason, when you enter the username/password and hit “Login,” it is redirecting me back to the login page instead of to the admin.php page. I’m new to creating login pages, so any advice would be appreciated.

Login Form

<?php 
	$title = "Login | The Play Group Theatre";
?>
<?php include("../includes/head.php"); ?>
<link rel="stylesheet" type="text/css" href="/admin/css/screen.css" />

</head>

<body>

<div id="wrap">
<?php include("../includes/nav-top.php"); ?>
<?php include("../includes/header.php"); ?>
<?php include("../includes/nav-main.php"); ?>
	<div id="section">
		<div id="article">
			<h2>Member Login</h2>
			<form name="login" action="login.php" method="post">
				<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>
				<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>
				<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>
			</form>
			<h2>New User</h2>
			<form name="register" action="register.php" method="post">
				<div><label for="regusername">Username<br /><input type="text" id="regusername" name="regusername" /></label></div>
				<div><label for="pass1">Password<br /><input type="password" id="pass1" name="pass1" /></label></div>
				<div><label for="pass2">Repeat Password<br /><input type="password" id="pass2" name="pass2" /></label></div>
				<div><input type="submit" id="submitregister" name="submitregister" value="Register" /></div>
			</form>
		</div>
	</div>
<?php include("../includes/footer.php"); ?>
</div>

</body>

</html>

Processing Code

<?php
	if (isset($_POST['submitlogin'])) {
		// Gather variables
		$username = $_POST['username'];
		$password = $_POST['password'];
		$host = 'localhost';
		$db_username = '*********';
		$db_password = '*********';
		$db = '*********';
		$table = 'users';
		// Create error array
		$errors = array();
		// Check validity of username
		if (isset($username)) {
			$username = stripslashes($username);
		} else {
			$username = NULL;
			$errors[] = "You must enter a username.";
		}
		// Check validity of password
		if (isset($password)) {
			$password = stripslashes($password);
		} else {
			$password = NULL;
			$errors[] = "You must enter a password.";
		}
		$password_encrypted = md5($password);
		// If there are no errors
		if (empty($errors)) {
			// Connect to database
			mysql_connect("$host", "$db_username", "$db_password") or die ("We cannot connect to the database at this time.  Please consult your web developer for more details.");
			mysql_select_db("$db")or die("We cannot select the proper database at this time.  Please consult your web developer for more details.");
			// Query users table
			$sql = 'SELECT * FROM ' . $table . ' WHERE username="' . $username . '" and password="' . $password_encrypted . '"';
			$result = mysql_query($sql);
			$count = mysql_num_rows($result);
			if ($count == 1) {
				// Register $myusername, $mypassword and redirect to file "admin.php"
				$_SESSION['username'];
				$_SESSION['password'];
				header("location: admin.php");
			} else {
				echo '<div class="error">Wrong Username or Password</div>';
				echo '<form name="login" action="login.php" method="post">';
				echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
				echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
				echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
				echo '</form>';
			}
		} else {
			echo '<div class="error">';
			echo '<ul>';
			foreach ($errors as $specific) {
				echo '<li>' . $specific . '</li>';
			}
			echo '</ul>';
			echo '</div>';
			echo '<form name="login" action="login.php" method="post">';
			echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
			echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
			echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
			echo '</form>';
		}
	} else {
		header("location: index.php");
	}
?>

<?php
$title = “Login | The Play Group Theatre”;
?>
<?php include(“…/includes/head.php”); ?>

Just for humor sake… make that all 1 PHP block, and see if you still get the issue.

PS: Session variables wont do anything if you dont call session_start …

I’ve tested your code, except for the connection to the database.

Your sql query syntax is ok and the data from the form is coming over ok.

Therefore, for some reason

 
if ($count == 1) 

$count is not equal to 1 for mysql_num_rows($result).

Make sure you are connected to the database when you run thw query and that the table and column names in $sql are correct and that the username and encrypted passwords exist in your database.

for a user name = xxx and password = yyy

your $sql evaluates to


SELECT * FROM users WHERE username="xxx" and password="f0a4058fd33489695d53df156b77c724" 

I just ran the script again, echoing $count, and it came to 1, so I know that’s not the issue.

<?php
$title = "Login | The Play Group Theatre";
?>
<?php include("../includes/head.php"); ?>

I also moved this all into one PHP block, and that didn’t do anything as well.

My connection to the database is okay because it ran through the script far enough for me to echo $count, so I know that’s okay.

Really confused as to what’s going on. Any more advice?

I assume admin.php looks for the session variables. Have you tried telling your script to start a session before trying to set them? (Should be line 1 of your head.php file!!!)

And… what is this doing there…
header(“location: index.php”);
?
Seems to be an infinite loop to me, but i could be wrong (Browser might short-circuit the loop)

ok, if $count = 1 then at least we know the database connection is ok and the query works :slight_smile:

Now, you will definitely need

 
<?php
[COLOR=red]session_start();[/COLOR]

up the top of every php page where you are using sessions.

Also, header() will only work if there is no previous output from your php script before the header() statement.

This can be a real pain because blank lines in your code and trailing blank spaces in your code lines can be seen as output.

But you will also need

 
die();

after the header() statement to stop the rest of the original script from executing after the header() is executed.

if adding die() after header() still doesn’t fix the problem then check if

 
header("location: admin.php");

is the problem, by replacing it with javascript (which will definitely work if you have js enabled)

 
echo '<script type="text/javascript">window.location.href="admin.php";</script>';
 
die();

 
header("location: index.php");

is in the false part of the

 
 if (isset($_POST['submitlogin'])) {

which evaluates to true when I test the code and so

 
header("location: index.php");

doesn’t get executed

Okay, here’s where I’m at.

And… what is this doing there…
header(“location: index.php”);
?
Seems to be an infinite loop to me, but i could be wrong (Browser might short-circuit the loop)

I removed the infinite loop from the bottom of the script.

I also added die(); after the header in the middle of the script.

I also checked for whitespace before, after and within the PHP, and there is none.

It still doesn’t seem to be working. Here’s the updated login.php file:

<?php
	if (isset($_POST['submitlogin'])) {
		// Gather variables
		$username = $_POST['username'];
		$password = $_POST['password'];
		$host = 'localhost';
		$db_username = '*********';
		$db_password = '*********';
		$db = '*********';
		$table = 'users';
		// Create error array
		$errors = array();
		// Check validity of username
		if (isset($username)) {
			$username = stripslashes($username);
		} else {
			$username = NULL;
			$errors[] = "You must enter a username.";
		}
		// Check validity of password
		if (isset($password)) {
			$password = stripslashes($password);
		} else {
			$password = NULL;
			$errors[] = "You must enter a password.";
		}
		$password_encrypted = md5($password);
		// If there are no errors
		if (empty($errors)) {
			// Connect to database
			mysql_connect("$host", "$db_username", "$db_password") or die ("We cannot connect to the database at this time.  Please consult your web developer for more details.");
			mysql_select_db("$db")or die("We cannot select the proper database at this time.  Please consult your web developer for more details.");
			// Query users table
			$sql = 'SELECT * FROM ' . $table . ' WHERE username="' . $username . '" and password="' . $password_encrypted . '"';
			$result = mysql_query($sql);
			$count = mysql_num_rows($result);
			echo $count;
			if ($count == 1) {
				// Register $myusername, $mypassword and redirect to file "admin.php"
				$_SESSION['username'];
				$_SESSION['password'];
				header("location: admin.php");
				die();
			} else {
				echo '<div class="error">Wrong Username or Password</div>';
				echo '<form name="login" action="login.php" method="post">';
				echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
				echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
				echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
				echo '</form>';
			}
		} else {
			echo '<div class="error">';
			echo '<ul>';
			foreach ($errors as $specific) {
				echo '<li>' . $specific . '</li>';
			}
			echo '</ul>';
			echo '</div>';
			echo '<form name="login" action="login.php" method="post">';
			echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
			echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
			echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
			echo '</form>';
		}
	}
?>
 
header("location: index.php");


was not in an infinite loop as I explained earlier, but that is beside the point.

Where is session_start() you were advised by more than 1 poster you will need?

if that doesn’t fix the problem then try replacing the header() statement with the javascript I suggested earlier. That will tell you if the problem is with the header() statement or not.

Took all of your advice, and still not working. I will repost all code again with edits.

Processing Code

<?php
	session_start();
	if (isset($_POST['submitlogin'])) {
		// Gather variables
		$username = $_POST['username'];
		$password = $_POST['password'];
		$host = 'localhost';
		$db_username = '*********';
		$db_password = '*********';
		$db = '*********';
		$table = 'users';
		// Create error array
		$errors = array();
		// Check validity of username
		if (isset($username)) {
			$username = stripslashes($username);
		} else {
			$username = NULL;
			$errors[] = "You must enter a username.";
		}
		// Check validity of password
		if (isset($password)) {
			$password = stripslashes($password);
		} else {
			$password = NULL;
			$errors[] = "You must enter a password.";
		}
		$password_encrypted = md5($password);
		// If there are no errors
		if (empty($errors)) {
			// Connect to database
			mysql_connect("$host", "$db_username", "$db_password") or die ("We cannot connect to the database at this time.  Please consult your web developer for more details.");
			mysql_select_db("$db")or die("We cannot select the proper database at this time.  Please consult your web developer for more details.");
			// Query users table
			$sql = 'SELECT * FROM ' . $table . ' WHERE username="' . $username . '" and password="' . $password_encrypted . '"';
			$result = mysql_query($sql);
			$count = mysql_num_rows($result);
			echo $count;
			if ($count == 1) {
				// Register $myusername, $mypassword and redirect to file "admin.php"
				$_SESSION['username'];
				$_SESSION['password'];
				echo '<script type="text/javascript">window.location.href="admin.php";</script>';
				die();
			} else {
				echo '<div class="error">Wrong Username or Password</div>';
				echo '<form name="login" action="login.php" method="post">';
				echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
				echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
				echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
				echo '</form>';
			}
		} else {
			echo '<div class="error">';
			echo '<ul>';
			foreach ($errors as $specific) {
				echo '<li>' . $specific . '</li>';
			}
			echo '</ul>';
			echo '</div>';
			echo '<form name="login" action="login.php" method="post">';
			echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
			echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
			echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
			echo '</form>';
		}
	}
?>

admin.php

<?php
	session_start();
	if (!isset($_SESSION['username'])) {
		header("location: index.php");
	}
	$title = "Admin | The Play Group Theatre";
?>
<?php include("../includes/head.php"); ?>
<link rel="stylesheet" type="text/css" href="/admin/css/screen.css" />

</head>

<body>

<div id="wrap">
<?php include("../includes/nav-top.php"); ?>
<?php include("../includes/header.php"); ?>
<?php include("../includes/nav-main.php"); ?>
	<div id="section">
		<div id="article">
			<p><a href="logout.php">Log Out >></a></p>
			<h2>Admin</h2>
		</div>
	</div>
<?php include("../includes/footer.php"); ?>
</div>

</body>

</html>

$_SESSION['username'];
$_SESSION['password'];

What is that supposed to do?
Hint: it doesn’t do anything

Also, never ever ever store a user’s password in a session! especially not unencrypted!
I guess that’s what the code above is supposed to do anyway …

it would help if you could post any error mesages or at least what happened/output to the screen when you ran the code.

Anyway,

the problem seem to be related to

 
if ([COLOR=#0000bb]$count [/COLOR][COLOR=#007700]== [/COLOR][COLOR=#0000bb]1[/COLOR][COLOR=#007700]) { [/COLOR]
[COLOR=#ff8000]// Register $myusername, $mypassword and redirect to file "admin.php" [/COLOR]
[COLOR=#0000bb]$_SESSION[/COLOR][COLOR=#007700][[/COLOR][COLOR=#dd0000]'username'[/COLOR][COLOR=#007700]]; [/COLOR]
[COLOR=#0000bb]$_SESSION[/COLOR][COLOR=#007700][[/COLOR][COLOR=#dd0000]'password'[/COLOR][COLOR=#007700]]; [/COLOR]
[COLOR=#007700]              echo [/COLOR][COLOR=#dd0000]'<script type="text/javascript">window.location.href="admin.php";</script>'[/COLOR][COLOR=#007700]; [/COLOR]
[COLOR=#007700]              die(); [/COLOR]
[COLOR=#007700]          }[/COLOR]

  1. the session variables should be assigned a value.

$_SESSION[‘username’] = $username;

also, imho you can remove $_SESSION[‘password’];

  1. I would use another session var to validate the login on each page after login, for example
 
$_SESSION['logged_in'] = 'fe25hfg4@';

and check for this session var and value on each sessioned page to check if the user is legitimately logged in or not. (but this is not the cause of your problem)

In admin.php add the following debugging line just to check if it get’s to that page


[COLOR=#0000bb][COLOR=#0000bb]<?php [/COLOR]
[COLOR=#0000bb]  session_start[/COLOR][COLOR=#007700]();[/COLOR]
 
[COLOR=#007700]  echo '<h2>got inside admin.php<h2>';   [/COLOR]
[/COLOR]
Off Topic:

btw - there are other security issues with your code, if this is for a “reall life” application, but they can be dealt with after you fix the login process.

Best to keep to the KISS pronciple for now.

Okay, it’s working now. Thank you so much for your help!

You mentioned that there are some “security issues” with my code. This is a project that I would like to go live when it is complete, so any advice that you could give me about the code would be amazing. Like I said, very new to this, and definitely am not secure with all of what I have done. I will repost code again. Maybe you could take a look and give me some advice?

Also, not sure I understand how to use the $_SESSION[‘logged_in’] variable that you mentioned. Could you explain this?

Thanks again! This has been a great learning experience!

<?php
	session_start();
	if (isset($_POST['submitlogin'])) {
		// Gather variables
		$username = $_POST['username'];
		$password = $_POST['password'];
		$host = 'localhost';
		$db_username = '*********';
		$db_password = '*********';
		$db = '*********';
		$table = 'users';
		// Create error array
		$errors = array();
		// Check validity of username
		if (isset($username)) {
			$username = stripslashes($username);
		} else {
			$username = NULL;
			$errors[] = "You must enter a username.";
		}
		// Check validity of password
		if (isset($password)) {
			$password = stripslashes($password);
		} else {
			$password = NULL;
			$errors[] = "You must enter a password.";
		}
		$password_encrypted = md5($password);
		// If there are no errors
		if (empty($errors)) {
			// Connect to database
			mysql_connect("$host", "$db_username", "$db_password") or die ("We cannot connect to the database at this time.  Please consult your web developer for more details.");
			mysql_select_db("$db")or die("We cannot select the proper database at this time.  Please consult your web developer for more details.");
			// Query users table
			$sql = 'SELECT * FROM ' . $table . ' WHERE username="' . $username . '" and password="' . $password_encrypted . '"';
			$result = mysql_query($sql);
			$count = mysql_num_rows($result);
			echo $count;
			if ($count == 1) {
				// Register $myusername, $mypassword and redirect to file "admin.php"
				$_SESSION['username'] = $username;
				$_SESSION['logged_in'] = 'fe25hfg4@';
				echo '<script type="text/javascript">window.location.href="admin.php";</script>';
				die();
			} else {
				echo '<div class="error">Wrong Username or Password</div>';
				echo '<form name="login" action="login.php" method="post">';
				echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
				echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
				echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
				echo '</form>';
			}
		} else {
			echo '<div class="error">';
			echo '<ul>';
			foreach ($errors as $specific) {
				echo '<li>' . $specific . '</li>';
			}
			echo '</ul>';
			echo '</div>';
			echo '<form name="login" action="login.php" method="post">';
			echo '<div><label for="username">Username<br /><input type="text" id="username" name="username" /></label></div>';
			echo '<div><label for="password">Password:<br /><input type="password" id="password" name="password" /></label></div>';
			echo '<div><input type="submit" id="submitlogin" name="submitlogin" value="Login" /></div>';
			echo '</form>';
		}
	}
?>
<?php
	session_start();
	if (!isset($_SESSION['username'])) {
		header("location: index.php");
	}
	$title = "Admin | The Play Group Theatre";
?>
<?php include("../includes/head.php"); ?>
<link rel="stylesheet" type="text/css" href="/admin/css/screen.css" />

</head>

<body>

<div id="wrap">
<?php include("../includes/nav-top.php"); ?>
<?php include("../includes/header.php"); ?>
<?php include("../includes/nav-main.php"); ?>
	<div id="section">
		<div id="article">
			<p><a href="logout.php">Log Out >></a></p>
			<h2>Admin</h2>
		</div>
	</div>
<?php include("../includes/footer.php"); ?>
</div>

</body>

</html>

glad it’s finally sorted out :drink::drink:

But the next step is to put back the original header() redirect instead of the “debugging” javascript redirect because users, albeit a very small number most likely, with javascript turned off in their browser will not be able to log in

If header() doesn’t work you will have to remove all blank lines and leading and trailing blank spaces in all your code lines above the header().

Regarding security -

imho this is a must read on SQL Injection

What I normally do with all user inputs (via forms or whatever) is to validate and sanitise them before putting them into any sql query.

  1. check that each input only contains valid characters for that input type…eg…a first name contains only letters

  2. sanitise each input using mysql_real_escape_string() before inserting it into the sql query. Another option is to use [URL=“http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html”]prepared statements. You must do one or the other.

  3. regarding S_SESSION[‘logged_in’] this session variable is set only once the entered username and password have been verified in the database and this session var is used to validate whether a user is logged in or not as they browse around your website.

Normally I would use a hard to guess key and value.

eg.

when $count = 1

you could set

 
$_SESSION['isUsrLegit'] = 'df3$@as34lkgy*'; 

and then on every page at the top you would have

 
<?php
session_start();
 
if(!isset($_SESSION['isUsrLegit']) || $_SESSION['isUsrLegit'] != 'df3$@as34lkgy*') {
    die('<p>You are not an authorised user</p>');
}

for added security you could also have multiple login validation session vars.

I would store the username in a session var only if you want to display the username on each page for some reason, for example on each page as the user browsers yuo could have

 
echo '<p>Welcome: '.$_SESSION['username'].'</p>';

Kalon,

Thanks so much for all of the great advice. I feel so much better about this script now. I implemented everything you mentioned above. I really appreciate the time you took to look everything over for me.

Thanks!

that’s ok :slight_smile: