Jump to content

administrator login


captain_scarlet87

Recommended Posts

Hi, I am trying to create a login so that admin users are displayed different menu links compared to a normal user when logged in. I have given admin users the value of 1 in a database table and normal users 0.

 

At the moment an admin user can login in as there name is displayed however the wrong links are displayed.

 

Here is the code I am working with. Thanks.

 

footer.html:

 

<!-- End of Content -->
</div>

<div id="Menu">
<a href="index.php">Home</a><br />
<?php # Script 13.2 - footer.html
// This page completes the HTML template.

// Display links based upon the login status.
// Show LOGIN links if this is the LOGOUT page.
if (isset($_SESSION['admin'])  && ($_SESSION['admin'] === 1) AND (substr($_SERVER['PHP_SELF'], -10) != 'logout.php')) {
echo '<a href="logout.php">Logout</a><br />
<a href="change_password.php">Change Password</a><br />
<a href="upload_instructions.php">Upload Instructions</a><br />
';
} else { //  Not logged in.
echo '	<a href="register.php">Create User</a><br />
<a href="login.php">Login</a><br />
<a href="forgot_password.php">Forgot Password</a><br />
';
}

?>
</div>
</body>
</html>
<?php // Flush the buffered output.
ob_flush();
?>

 

login.php (where the session is created):

 

<?php # Script 13.8 - login.php
// This is the login page for the site.

// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');

// Set the page title and include the HTML header.
$page_title = 'Login';
include ('./includes/header.html');

if (isset($_POST['submitted'])) { // Check if the form has been submitted.

require_once ('../mysql_connect.php'); // Connect to the database.

// Validate the username.
if (!empty($_POST['username'])) {
	$fn = escape_data($_POST['username']);
} else {
	echo '<p><font color="red" size="+1">You forgot to enter your username!</font></p>';
	$fn = FALSE;
}

// Validate the password.
if (!empty($_POST['pass'])) {
	$p = escape_data($_POST['pass']);
} else {
	$p = FALSE;
	echo '<p><font color="red" size="+1">You forgot to enter your password!</font></p>';
}

if ($fn && $p) { // If everything's OK.

	// Query the database.
	$query = "SELECT username, admin FROM users WHERE (username='$fn' AND pass=SHA('$p'))";
	$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

	if (@mysql_num_rows($result) == 1) { // A match was made.

		// Register the values & redirect.
		$row = mysql_fetch_array ($result, MYSQL_NUM);
		mysql_free_result($result);
		mysql_close(); // Close the database connection.
		$_SESSION['admin'] = $row[1];
		$_SESSION['username'] = $row[0];

		// Start defining the URL.
		$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
		// Check for a trailing slash.
		if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
			$url = substr ($url, 0, -1); // Chop off the slash.
		}
		// Add the page.
		$url .= '/index.php';

		ob_end_clean(); // Delete the buffer.
		header("Location: $url");
		exit(); // Quit the script.

	} else { // No match was made.
		echo '<p><font color="red" size="+1">The username and password entered do not match those on file.</font></p>';
	}

} else { // If everything wasn't OK.
	echo '<p><font color="red" size="+1">Please try again.</font></p>';
}

mysql_close(); // Close the database connection.

} // End of SUBMIT conditional.
?>

<h1>Login</h1>
<p>Your browser must allow cookies in order to log in.</p>
<form action="login.php" method="post">
	<fieldset>
	<p><b>Username:</b> <input type="text" name="username" size="30" maxlength="30" /></p>
	<p><b>Password:</b> <input type="password" name="pass" size="20" maxlength="20" /></p>
	<div align="center"><input type="submit" name="submit" value="Login" /></div>
	<input type="hidden" name="submitted" value="TRUE" />
	</fieldset>
</form>

<?php // Include the HTML footer.
include ('./includes/footer.html');
?>

Link to comment
Share on other sites

I know this is pretty much a given, but have you checked to make sure your database's admin field is set to 1 for that user?

 

And also, I'm not sure if this would cause any problems or not, but since the mysql_close is closed before you set the variables... would that create an issue? (a seasoned pro will hopefully answer this =)

// Register the values & redirect.
		$row = mysql_fetch_array ($result, MYSQL_NUM);
		mysql_free_result($result);
		mysql_close(); // Close the database connection.
		$_SESSION['admin'] = $row[1];
		$_SESSION['username'] = $row[0];

 

And as Aeroswat noted, change the if statement to admin==1 instead of ===.

 

Other than that that's the only issues I see.

 

Joey

Link to comment
Share on other sites

I know this is pretty much a given, but have you checked to make sure your database's admin field is set to 1 for that user?

 

And also, I'm not sure if this would cause any problems or not, but since the mysql_close is closed before you set the variables... would that create an issue? (a seasoned pro will hopefully answer this =)

// Register the values & redirect.
		$row = mysql_fetch_array ($result, MYSQL_NUM);
		mysql_free_result($result);
		mysql_close(); // Close the database connection.
		$_SESSION['admin'] = $row[1];
		$_SESSION['username'] = $row[0];

 

And as Aeroswat noted, change the if statement to admin==1 instead of ===.

 

Other than that that's the only issues I see.

 

Joey

 

No I believe mysql_fetch_array will return actual values instead of references so closing it shouldn't be a problem since $row is a regular php array and has nothing to do with the database link.

Link to comment
Share on other sites

I know this is pretty much a given, but have you checked to make sure your database's admin field is set to 1 for that user?

 

And also, I'm not sure if this would cause any problems or not, but since the mysql_close is closed before you set the variables... would that create an issue? (a seasoned pro will hopefully answer this =)

// Register the values & redirect.
		$row = mysql_fetch_array ($result, MYSQL_NUM);
		mysql_free_result($result);
		mysql_close(); // Close the database connection.
		$_SESSION['admin'] = $row[1];
		$_SESSION['username'] = $row[0];

 

And as Aeroswat noted, change the if statement to admin==1 instead of ===.

 

Other than that that's the only issues I see.

 

Joey

 

No I believe mysql_fetch_array will return actual values instead of references so closing it shouldn't be a problem since $row is a regular php array and has nothing to do with the database link.

 

Oh okay, I figured it would be that but I threw it out there because I wasn't 100% sure.

Link to comment
Share on other sites

@op

 

Is your server setup to interpret .html files as PHP files? If not, change your "footer.html" file to "footer.php" and your include statement accordingly.

 

@aeroswat

 

=== compares the datatype equality of the arguments aswell as value equality, aslong as both are integers it should be ok.

 

@OP I would change it to == or cast to int tho if your mysql field isnt set to int.

 

@jdorma0

 

The query result resource is already returned (by mysql_query) and the database link is no longer needed, it doesn't matter weather the connection is closed at this point.

 

Link to comment
Share on other sites

Removing the extra = worked, thank you very much!

 

As that is now working I attempted to make a new admin user using the code below however it keeps on setting the value to 0 in the db even when the radio button Yes should carry the value 1. Had this working a while ago but must have accidently changed something at some point but can't see what. I'm using phpMyAdmin and have the admin field set to tinyint.

 

If you can help with this as well that would be great.

 

register.php

 

<?php # Script 13.6 - register.php
// This is the registration page for the site.

// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');

// Set the page title and include the HTML header.
$page_title = 'Register';
include ('./includes/header.html');

if (isset($_POST['submitted'])) { // Handle the form.

require_once ('../mysql_connect.php'); // Connect to the database.

// Check for a username.
if (eregi ('^[[:alpha:]\.\' \-]{2,30}$', stripslashes(trim($_POST['username'])))) {
	$fn = escape_data($_POST['username']);
} else {
	$fn = FALSE;
	echo '<p><font color="red" size="+1">Please enter your username!</font></p>';
}

// Check for an email address.
if (eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email'])))) {
	$e = escape_data($_POST['email']);
} else {
	$e = FALSE;
	echo '<p><font color="red" size="+1">Please enter a valid email address!</font></p>';
}

// Check for a password and match against the confirmed password.
if (eregi ('^[[:alnum:]]{4,20}$', stripslashes(trim($_POST['password1'])))) {
	if ($_POST['password1'] == $_POST['password2']) {
		$p = escape_data($_POST['password1']);
	} else {
		$p = FALSE;
		echo '<p><font color="red" size="+1">Your password did not match the confirmed password!</font></p>';
	}
} else {
	$p = FALSE;
	echo '<p><font color="red" size="+1">Please enter a valid password!</font></p>';
}

if ($fn && $e && $p) { // If everything's OK.

	// Make sure the email address is available.
	$query = "SELECT username FROM users WHERE email='$e'";
	$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

	if (mysql_num_rows($result) == 0) { // Available.

		// Add the user.
		$query = "INSERT INTO users (email, pass, username) VALUES ('$e', SHA('$p'), '$fn' )";
		$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

		if (mysql_affected_rows() == 1) { // If it ran OK.

			// Finish the page.
			echo '<h3>Thank you for registering!</h3>';
			include ('./includes/footer.html'); // Include the HTML footer.
			exit();

		} else { // If it did not run OK.
			echo '<p><font color="red" size="+1">You could not be registered due to a system error. We apologize for any inconvenience.</font></p>';
		}

	} else { // The email address is not available.
		echo '<p><font color="red" size="+1">That email address has already been registered. If you have forgotten your password, use the link to have your password sent to you.</font></p>';
	}

} else { // If one of the data tests failed.
	echo '<p><font color="red" size="+1">Please try again.</font></p>';
}

mysql_close(); // Close the database connection.

} // End of the main Submit conditional.
?>

<h1>Register</h1>
<form action="register.php" method="post">
<fieldset>

<p><b>Username:</b> <input type="text" name="username" size="30" maxlength="30" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" /></p>

<p><b>Email Address:</b> <input type="text" name="email" size="40" maxlength="40" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /> </p>

<p><b>Administrator? </b> <input type="radio" name="admin" value="1" /> Yes <input type="radio" name="admin" value="0" checked/> No </p>

<p><b>Password:</b> <input type="password" name="password1" size="20" maxlength="20" /> <small>Use only letters and numbers. Must be between 4 and 20 characters long.</small></p>

<p><b>Confirm Password:</b> <input type="password" name="password2" size="20" maxlength="20" /></p>
</fieldset>

<div align="center"><input type="submit" name="submit" value="Register" /></div>
<input type="hidden" name="submitted" value="TRUE" />

</form>

<?php // Include the HTML footer.
include ('./includes/footer.html');
?>

Link to comment
Share on other sites

@op

 

Is your server setup to interpret .html files as PHP files? If not, change your "footer.html" file to "footer.php" and your include statement accordingly.

 

@aeroswat

 

=== compares the datatype equality of the arguments aswell as value equality, aslong as both are integers it should be ok.

 

@OP I would change it to == or cast to int tho if your mysql field isnt set to int.

 

@jdorma0

 

The query result resource is already returned (by mysql_query) and the database link is no longer needed, it doesn't matter weather the connection is closed at this point.

 

Not a whole lot of people use integers as datatypes unless math needs to be done on them I believe. Better to assume the other way :) I didn't know that about triple equal tho. Thanks for the education

Link to comment
Share on other sites

@OP

When you insert the data into your database I don't see anywhere that specify the  insert value into the admin field.

 

         // Add the user.
         $query = "INSERT INTO users (email, pass, username) VALUES ('$e', SHA('$p'), '$fn' )";
         $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

 

$admin = (int)$_POST['admin'];

         // Add the user.
         $query = "INSERT INTO users (email, pass, username, admin) VALUES ('$e', SHA('$p'), '$fn', $admin )";
         $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.