Jump to content

Login Form Trouble


Xtremer360

Recommended Posts

I'm not sure where the issue really lies after the form submits it DOES perform the error messages if there is one, however if the username and password are atleast filled in and the user clicks Log In it doesn't do anything after that. 

 

login.php

<?php

/**
* @author Jeff Davidson
* @copyright 2010
*/

if (isset($_POST['submitted'])) {
    
    require_once ('inc/login_functions.php');
    require_once ('inc/dbconfig.php');
    list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']);
    
    if ($check) { // OK!
    
    // Set the session data:.
    session_start();
    $_SESSION['id'] = $data['id'];
    $_SESSION['firstname'] = $data['firstname'];
    
    // Redirect:
    $url = absolute_url ('loggedin.php');
    header("Location: $url");
    exit();
    
    }else {
    // Unsuccessful!
    $errors = $data;
    }
    
    mysqli_close($dbc);
    
} // End of the main submit conditional.

include ('inc/login_page.php')

?>

 

login_functions.php

<?php

/**
* @author Jeff Davidson
* @copyright 2010
*/

// This page defines two functions used by the login/logout process.

/* This function determines and returns an absolute URL.
* It takes one argument: the page that concludes the URL.
* The argument defaults to index.php.

*/

function absolute_url($page = 'index.php') {
    // Start defining the URL...
    // URL is http://plus the host name plus the current directory:
    $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    
    // Remove any trailing slashing:
    $url = rtrim($url, '/\\');
    
    // Add the page
    $url .= '/' . $page;
    
    // Return the URL:
    return $url;
    
} // End of absolute_url() function.


/* This function validates the form data (the username and password).
* If both are present, teh database is queried.
* The function requires a database connection.
* The function returns an array of information, including:
* - a TRUE/FALSE variable indicating success
* - an array of either errors or the database result
*/

function check_login($dbc, $username = '', $password = '') {
    $errors = array(); // Initialize error array.
    
    // Validate the username
    if (empty($username)) {
        $errors[] = 'You forgot to enter your username.';
    } else {
        $u = mysqli_real_escape_string($dbc, trim($username));
    }
    
    // Validate the password:
    if (empty($password)) {
        $errors[] = 'You forgot to enter your password.';
    } else {
        $p = mysqli_real_escape_string($dbc, trim($password));
    }
    
    if (empty($errors)) { // If everythings OK.
        
        // Retrieve the firstname and lastname for the username/password combination:
        $q = "SELECT id, firstname FROM users WHERE username='$u' AND password=SHA('$p')";
        $r = @mysqli_query($dbc, $q); // Run teh query.
        
        // Check the result:
        if (mysqli_num_rows($r) == 1) {
            
            // Fetch the record:
            $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
            
            // Return true and the record:
            return array(true, $row);
            
        }else { // Not a match!
        $errrors[] = 'The username and password entered do not match those on file.';
        }
    } // End of empty ($errrors) IF.
    
    // Return false and the errors:
    return array(false, $errors);
    
} //End of check_login() function.

?>

 

login_page.php

<?php

/**
* @author Jeff Davidson
* @copyright 2010
*/

// This page prints any errors associated with logging in and creates the login, including the form.

// Prints any error messages, if they exists:
if (!empty($errors)) {
    echo '<h1>Error!</h1>
    <p class="error">The following error(s) occured:<br />';
    foreach ($errors as $msg) {
        echo " - $msg<br />\n";
    }
    echo '</p><p>Please try again.</p>';
}

// Display the form:
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Caracole" />
<title>Titanium</title>
<link HREF="favicon.ico" type="image/x-icon" rel="icon" />
<link HREF="favicon.ico" type="image/x-icon" rel="shortcut icon" />
<link rel="stylesheet" type="text/css" href="css/tripoli.simple.css" media="screen, projection, print" />
<link rel="stylesheet" type="text/css" href="css/base.css" media="screen, projection, print" />
<link rel="stylesheet" type="text/css" href="css/layout.css" media="screen, projection, print" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen, projection, print" />
<link rel="stylesheet" type="text/css" href="css/theme.css" media="screen, projection, print" />
<link rel="stylesheet" type="text/css" href="css/icons.css" media="screen, projection, print" />
<script type="text/javascript" SRC="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//<![CDATA[
document.write('<link rel="stylesheet" type="text/css" href="css/js/js.css" media="screen, projection, print" />');
//]]>

$(document).ready(function(){

$(".close").click(function(){
	$(this).parents(".message").hide("puff");
});

});	


</script>
<!--[if IE]>
	<link rel="stylesheet" type="text/css" href="css/ie/ie.css" media="screen, projection, print" />
<![endif]-->
 <!--[if lt IE 7]>
<script src="js/DD_belatedPNG_0.0.7a-min.js" type="text/javascript"></script>
<script>

	DD_belatedPNG.fix(' #header, h1, h1 a, .close, .field,.paginate .current, .icon, .required-icon');

</script>
  <link rel="stylesheet" href="css/ie/ie6.css" type="text/css" media="screen, projection"/>
<![endif]-->
</head>
<body>
<!-- Content -->
<div id="login" class="content">	
	<div class="roundedBorders login-box">
		<!-- Title -->
		<div id="title" class="b2">
			<h2>Log In</h2>
			<!-- TitleActions -->
			<div id="titleActions">
				<div class="actionBlock">
				<a href="#">Forgot your password ?</a>
				</div>
			</div>
			<!-- /TitleActions -->
		</div>
		<!-- Title -->

		<!-- Inner Content -->
		<div id="innerContent">
			<form action="login.php" method="post">
				<div class="field">
					<label for="username">Username</label>
					<input type="text" class="text" id="username" name="username" />
				</div>
				<div class="field">
					<label for="password">Password</label>
					<input type="password" class="text" id="password" name="password"/>
				</div>
				<div class="clearfix login-submit">
					<span class="fleft">
						<input type="checkbox" name="remember-me" id="remember-me" />
						<label for="remember-me">Remember me</label>
					</span>
					<span class="fright">
						<button class="button" type="submit" name="submit"><strong>Log In</strong></button>
					</span>
				</div>
                    <input type="hidden" value="TRUE" name="submitted" />
			</form>
		</div>
		<!-- /Inner Content -->
		<div class="bBottom"><div></div></div>
	</div>
</div>

</body>
</html>

 

loggedin.php

<?php

/**
* @author Jeff Davidson
* @copyright 2010
*/

// The user is redirected here from login.php.

session_start(); // Star the session.

// If no session value is present, redirect the user:
if (!isset($_SESSION['id'])) {
    require_once('inc/login_functions.php');
    $url = absolute_url();
    header("Location: $url");
    exit();
}

$page_title = 'Logged In!';

// Print a customized message:
echo "<h1>Logged In!</h1>
<p>You are now logged in, {$_SESSION['firstname']}!</p>
<p><a href=\"logout.php\">Logout</a></p>";


?>

 

I thought I'd come back in and insert the file manager I have setup here.

 

root/loggedin.php

root/login.php

 

root/inc/login_page.php

root/inc/login_functions.php

 

Link to comment
Share on other sites

I'm wondering if it has to do with the password field in the database itself.  I have it has char(40) and when I went in and did a manual insert into my DB when I got to the password field I put in what I wanted my password to be and then I selected the SHA1 function. Is that what is complicating things for my login form?

Link to comment
Share on other sites

The fact that you have an @ on the mysqli_query() statement to suppress php errors from it, is a pretty good indication that the query is/was failing due to an error of some type. Why do you have that @ in your code?

 

but it is the correct username and password.

 

^^^ You might think that, but your code and the database disagrees. You would need to troubleshoot why your query is not matching one row in your database table.

Link to comment
Share on other sites

The fact that you have an @ on the mysqli_query() statement to suppress php errors from it, is a pretty good indication that the query is/was failing due to an error of some type. Why do you have that @ in your code?

 

but it is the correct username and password.

 

^^^ You might think that, but your code and the database disagrees. You would need to troubleshoot why your query is not matching one row in your database table.

 

That's just what I was reading out of the book I've been studying and learning up on. Should I not be doing that? Is what I reposted a second the possible problem ?

Link to comment
Share on other sites

So, you got this code from some book. Sadly, the code does not even have any logic to check if the query worked or not and it is in fact doing something (the @) that would prevent a php error with the query from being reported/displayed/logged.

 

You should remove any @'s that are in the code in front of statements. There's simply no reason for any code to have @'s in it. On a development system, display_errors should be ON because you want to know if there are any php errors occurring in the code so that you can find and fix them. On a live server, display_errors should be OFF and log_errors should be ON so that any php errors that might occur don't get displayed but they do get logged so that you can find and fix them. On both a development system and a live server, error_reporting should be at least E_ALL (using -1 is ever better since every php error category will be included) so that all the normal php detected errors will be displayed/logged.

 

Sorry to get side tracked on errors and error_reporting/display_errors/log_errors, but at this point you don't even know if the query executed or not. You may in fact have the correct data in your database, but if the query is failing due to some error, there is no result object in $r for mysqli_num_rows to even test and your code will never match that data in the database.

 

Short answer: When learning php or developing and debugging php code, you should have error_reporting set to E_ALL (or even better -1) and display_errors set to ON so that php will help you by reporting and displaying all the errors it finds.

Link to comment
Share on other sites

Wow that little @ symbol was what was preventing it from working correctly. After the login form submission it correctly goes to the loggedin.php file however why its not redirecting me to the admin panel which I have inside of /root folder called index.php file.

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.