Jump to content

Simple login form trouble.


Go to solution Solved by Ch0cu3r,

Recommended Posts

I'm trying to make a simple login form for my page. Here is my html:

<?php include "database.php"; ?>
<!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" />
<title>Olle's FileShare</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
	<?php include "view/header.php" ?>
	<div id="main">    
      
    <form method="post" action="database.php" name="loginform" id="loginform">  
    <fieldset>  
        <label for="username">Username:</label><input type="text" name="username" id="username" /><br />  
        <label for="password">Password:</label><input type="password" name="password" id="password" /><br />  
        <input type="submit" name="login" id="login" value="Login" />  
    </fieldset>  
    </form>   
    </div>
	
</body>
</html>

And this is my database.php file that connects to my umm... database. :

<?php
	
	$dsn= 'mysql:host=localhost; dbname=file_share';
    $username= 'root';
    $password= '';
    
    try {
    	$db= new PDO($dsn, $username, $password);
        echo '<p>You are connected to the database!</p>';
    } catch (PDOException $e) {
    	$error_message= $e->getMessage();
        echo "<p>An error occured while connecting to the database: $error_message </p>";
        }
		//Get the input from form
		$username= $_POST['username'];
		$userpassword= $_POST['password'];
		//Secure the input
		$username= mysql_real_escape_string($_POST['username']);
		$userpassword= mysql_real_escape_string($_POST['password']);
		
		//Check the input against the database
		$query = "SELECT COUNT(`username`) AS `total` FROM `user` WHERE `username` = '$username' AND `password` = '$userpassword'";
	    $result = mysql_query($query);
	    $row = mysql_fetch_assoc($result);
	   
	    if($row['total'] == 1) {
			$_SESSION['loggedIn']= "true";
			header("Location: index.php");
		}

?>

My database is called "file_share" while my table is called "users". Whenever i try to login, it says account not found. I know it's there as I created the table myself with only 2 users currently entered. Neither one works. Any help would be greatly appreciated!

Link to comment
https://forums.phpfreaks.com/topic/282663-simple-login-form-trouble/
Share on other sites

you are using the PDO database library for your database connection. you must use PDO statements throughout the rest of the code.

 

you need to have php's error_reporting set to E_ALL (always) and display_errors set to ON to get php to help you. each of the mysql_ database statements will be producing php errors that would have alerted you to the mismatch between your database connection using PDO and the rest of the statements not having a connection of the type they use.

the mysql_ extension is depreciated as of php5.5 and should not be used for new code.

 

you need to either use the mysqli or PDO database libraries.

 

there are countless examples posted all over the place. start with the basic examples posted in the php.net documentation.

Ok...this is what I came up with:

<?php
	
	$dsn= 'mysql:host=localhost; dbname=file_share';
    $username= 'root';
    $password= '';
    
    try {
    	$db= new PDO($dsn, $username, $password);
        echo '<p>You are connected to the database!</p>';
    } catch (PDOException $e) {
    	$error_message= $e->getMessage();
        echo "<p>An error occured while connecting to the database: $error_message </p>";
        }
		$sql= 'SELECT *
               FROM `Users`
               WHERE `Username` = :username
               AND `Password` = :password
               LIMIT 1';  //SQL query with named placeholders

        $stmt = $db->prepare($sql);  //Returns a PDOStatement class object
		
		if( isset($_POST['username'],$_POST['password'])
           && !empty($_POST['username']) && !empty($_POST['password']) )
{
              $username = $_POST['username'];
              $password = hash('md5',$_POST['password']);  
			  
			  $stmt->bindParam(':username',$username,PDO::PARAM_STR,16);
              $stmt->bindParam(':password',$password,PDO::PARAM_STR,16);
			  $stmt->execute();
              $result = $stmt->fetch(PDO::FETCH_ASSOC);
}
	   
	    if($stmt->rowCount() > 0) {
			$_SESSION['loggedIn']= "true";
			header("Location: index.php");
		}
		

?>

Now, this eliminated any error messages, and redirects to "index.php", but it doesn't matter what you put in for login or password...it just goes regardless.  ??

  • Solution

I have tested your code and it does work when the correct username/password is entered.

 

You need to debug your code firther to see where it is failing. Also you are md5 hashing the posted password, make sure the passwords in the database are also hd5 hashed and not plain text. The query needs to compare the md5 hashes.

 

I have modified your code so it spits out what it is doing as it processes the login. This is the sort of debug steps you need to take when code doesn't work the way you expect it to.

<?php
	
	$dsn= 'mysql:host=localhost; dbname=softlearner';
    $username= 'root';
    $password= 'root';
    
    try {
    	$db= new PDO($dsn, $username, $password);
        echo '<p>You are connected to the database!</p>';
    } catch (PDOException $e) {
    	$error_message= $e->getMessage();
        echo "<p>An error occured while connecting to the database: $error_message </p>";
    }

// only run code below if form has been posted
if($_SERVER['REQUEST_METHOD'] == 'POST') {

	/* Debug */
    printf('What is in $_POST <pre>%s</pre>', print_r($_POST, true));

	if( isset($_POST['username'], $_POST['password'])
        && !empty($_POST['username']) && !empty($_POST['password']) )
	{
        $username = $_POST['username'];
        $password = hash('md5',$_POST['password']);  

        printf('Credentials: <pre>%s</pre>', print_r(array('username' => $username, 'password' => $password), true));

        $sql= 'SELECT *
           FROM `members`
           WHERE `Username` = :username AND `Password` = :password
           LIMIT 1';  //SQL query with named placeholders

    	$stmt = $db->prepare($sql);  //Returns a PDOStatement class object
			  
		$stmt->bindParam(':username',$username,PDO::PARAM_STR,16);
        $stmt->bindParam(':password',$password,PDO::PARAM_STR,16);
		$stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
	}

	/* debug line */
	$error = $stmt->errorInfo();
	if($error[0] != '00000')
		printf('SQL Error: <pre>%s</pre>', print_r($error, true));
	/* end debug line */

	if($stmt->rowCount() > 0) {
		/*$_SESSION['loggedIn']= "true";
		header("Location: index.php");*/
		echo 'Login ok';
	}
	else
	{
		echo 'Sorry username/password wrong';
	}
}
else
{
	echo 'No post data received';
}
?>
Edited by Ch0cu3r
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.