PHP Tutorial: Register and Login (User Account System) 3

Post here is you are having problems with any of the tutorials.
Post Reply
roxy503
Posts: 5
Joined: Tue Aug 20, 2013 6:20 pm

PHP Tutorial: Register and Login (User Account System) 3

Post by roxy503 »

I'm having troubles getting Users and Passwords to come up in the database. I can't figure out what is wrong with my code. I would be on the register.php page and when i try and register it would say "You are not logged in as "roxy503" Logout?"

Everything else seems to run and it brings me to the protected.php page of the site. I followed the tutorial pretty closely as well. Here's the code along with a screenshot database.

register.php
<?php
 
include('core/init.inc.php');
 
$errors = array();
 
if (isset($_POST['username'], $_POST['password'], $_POST['repeat_password'])){
        if (empty($_POST['username'])){
                $errors[] = 'The username cannot be empty.';
        }
       
        if (empty($_POST['password']) || empty($_POST['repeat_password'])){
                $errors[] = 'The password cannot be empty.';
        }
       
        if ($_POST['password'] !== $_POST['repeat_password']){
                $errors[] = 'Password verification failed.';
        }
       
        if (user_exists($_POST['username'])){
                $errors[] = 'The username you entered is already taken.';
        }
       
        if (empty($errors)){
                add_user($_POST['username'], $_POST['password']);
               
                $_SESSION['username'] = htmlentities($_POST['username']);
               
                header('Location: protected.php');
                die();
               
        }
               
       
}
 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <!--<link rel="stylesheet" type="text/css" href="ext/css/style.css" />-->
                <title></title>
        </head>
        <body>
                <div>
                        <?php
 
                        if (empty($errors) === false){
                                ?>
                                <ul>
                                        <?php
 
                                        foreach ($errors as $error) {
                                                echo "<li>{$error}</li>";
                                        }
 
                                        ?>
                                </ul>
                                <?php
                        }
 
                        ?>
                </div >
                <form action="" method="post">
                        <p>
                                <label for="username">Username:</label>
                                <input type="text" name="username"  id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']) ?>" />
                        </p>
                        <p>
                                <label for="password">Password:</label>
                                <input type="password" name="password"  id="password" />
                        </p>
                        <p>
                                <label for="repeat_password">Confirm Password:</label>
                                <input type="password" name="repeat_password"  id="repeat_password" />
                        </p>
                        <p>
                                <input type="submit" value="Register" />
                        </p>
                </from>
        </body>
</html>
init.inc.php
<?php
 
session_start();
 
$exceptions = array('register','login');
 
$page = substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);
 
if (in_array($page, $exceptions) === false){
        if (isset($_SESSION['username']) === false){
                header('Location: login.php');
                die();
        }
}
 
mysql_connect("sample_server","roxy503","sample_pass");
mysql_select_db('roxy503');


$path = dirname(__FILE__);

include("{$path}/inc/user.inc.php");

?>
user.inc.php
<?php
 
// Checks to see if the username exists.
function user_exists($user){
        $user = mysql_real_escape_string($user);
 
        $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'");
 
        return (mysql_result($total, 0) == '1') ? true : false;

}
 echo mysql_error();
// Checks if the Username and Password combination is valid.
function valid_credentials($user, $pass){
        $user = mysql_real_escape_string($user);
        $pass = sha1($pass);
       
        $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND 'user_password' = '{$pass}'");
       
        return (mysql_result($total, 0) == '1') ? true : false;
}
 
//  Adds a user to the database.
function add_user($user, $pass){
        $user = mysql_real_escape_string(htmlentities($user));
        $pass = sha1($pass);
       
        mysql_query("INSERT INTO `users` (`user_password`) VALUES ('{$user}', '{$pass}')");
}
 
?>
Image
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by Temor »

in add_user you're only inserting data into user_password, not user_name.
function add_user($user, $pass){
        $user = mysql_real_escape_string(htmlentities($user));
        $pass = sha1($pass);
       
        mysql_query("INSERT INTO `users` (`user_password`) VALUES ('{$user}', '{$pass}')");
}
function add_user($user, $pass){
        $user = mysql_real_escape_string(htmlentities($user));
        $pass = sha1($pass);
       
        mysql_query("INSERT INTO `users` (`user_name`,`user_password`) VALUES ('{$user}', '{$pass}')");
}
Oh, and by the way, you might want to clear your session between the attempts at registering. If something is wrong but it still sets your $_SESSION data it could mess things up.

Create logout.php and put this code in it:
session_destroy();
roxy503
Posts: 5
Joined: Tue Aug 20, 2013 6:20 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by roxy503 »

Great! Now the script is add users to the table. But my problem now is that after I register, it keeps telling me that the username/password is incorrect.
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by ExtremeGaming »

<?php
// Checks if the Username and Password combination is valid.
function valid_credentials($user, $pass){
        $user = mysql_real_escape_string($user);
        $pass = sha1($pass);
       
        $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND 'user_password' = '{$pass}'");
       
        return (mysql_result($total, 0) == '1') ? true : false;
}
 
?>
You have apostropes (') instead of backticks (`) around user_password in your query here.
<?php while(!$succeed = try()); ?>
roxy503
Posts: 5
Joined: Tue Aug 20, 2013 6:20 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by roxy503 »

Man you guys are so awesome. I need to get better at finding these errors. Okay, one last thing that I've run into is that once I try to log in, instead of taking me to protected.php, it redirects me back to login.php, which I think there is something wrong with my init.inc.php script.
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by ExtremeGaming »

Could you post the contents of login.php please? It might just be my eyes not seeing code for a few months but everything seems okay in init.inc.php
<?php while(!$succeed = try()); ?>
roxy503
Posts: 5
Joined: Tue Aug 20, 2013 6:20 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by roxy503 »

Here is the code from the Login.php

<?php

include('core/init.inc.php');

$errors = array();

if (isset($_POST['username'], $_POST['password'])){
	if (empty($_POST['username'])){
		$errors[] = 'The username cannot be empty.';
	}

	if (empty($_POST['password'])){
		$errors[] = 'The password cannot be empty.';
	}

	if (valid_credentials($_POST['username'], $_POST['password']) === false){
		$errors[] = 'Username / Password incorrect.';
	}

	if (empty($errors)){
		$SESSION['username'] = htmlentities($_POST['username']);

		header('Location: protected.php');
		die();
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xtml">
	<head>
		<meta http-equiv="Content-Type" conent="text/html; charset=utf-8" />
		<link rel ="stylesheet" type="text/css" href="ext/css/style.css" />
		<title></title>
	</head>
	<body>
		<div>
			<?php

			if (empty($errors) === false){
				?>
		     <ul>
		     	<?php

		     	foreach($errors as $error){
		     		echo "<li>{$error}</li>";
		     	}

		     	?>
		     </ul>
		     <?php
		     }else{
		     	echo 'Need an account ? <a href="register.php">Register here</a>';
		     }


			?>
			
		</div>
		<form action="" method="post"
		<p>
			<label for="username">Username:</label>
			<input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']) ?>" />
		</p>
		<p>
			<label for="password">Password:</label>
			<input type="password" name="password" id="password" />
		</p>
		<p>
			<input type="submit" value="Login" />
		</p>
		</form>
	</body>
</html>	
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by ExtremeGaming »

<?php

	if (empty($errors)){
		$SESSION['username'] = htmlentities($_POST['username']);

		header('Location: protected.php');
		die();
	}
?>
You are missing the underscore in $_SESSION['username'] here.
<?php while(!$succeed = try()); ?>
roxy503
Posts: 5
Joined: Tue Aug 20, 2013 6:20 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by roxy503 »

Thank you so much! Learning PHP is so tedious. How long did it take you to be able to catch mistakes like that?
ExtremeGaming
Posts: 205
Joined: Mon Jul 09, 2012 11:13 pm

Re: PHP Tutorial: Register and Login (User Account System) 3

Post by ExtremeGaming »

I started learning to spot the little things by reading error messages. Helx has posted a nice thread of how to do some debugging here. It still took me a few weeks to learn how to debug without using it. Everyone has to start from somewhere so don't feel discouraged if you don't pick it up right away.
<?php while(!$succeed = try()); ?>
Post Reply