Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To create a login form using php, mysql and html

Tags:

php

mysql

I want to create a working login form. Here's what I have done and this displays cannot select db.

Edited login.php file

<?php
    error_reporting(E_ALL);
    //Connection Variables:
    $dbhost = "localhost";
    $dbname = "";
    $dbuser = "";
    $dbpass = "";
try{
    //Connection to SQL:
        $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
    //Error messagin enabled:
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $e)
    {
        echo $e->getMessage();
    }


    $user = '';
    $pass = '';
    $sum = 0;
    $error_msg = "Please type a username and a password";
    if(isset($_POST['login']))
    {
        //Start a session:
        session_start();

        $user = $_POST['email'];
        $pass = $_POST['password'];
        if(empty($user) && empty($pass))
        {
            echo $error_msg;
            $pass = '';
        }
        if(empty($user) || empty($pass))
        {
            echo $error_msg;
            $user = '';
            $pass = '';
        }
        if(!empty($user) && !empty($pass))
        {
            //SQL:
            $query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
            $query->bindParam(":u", $user);
            $query->bindParam(":p", $pass);
            //Execute query:
            $query->execute();
            $number_rows = $query->fetch(PDO::FETCH_NUM);
            if($number_rows>0)
            {
                echo $user;
                $_SESSION['usern'] = $user;
                $_SESSION['passw'] = $pass;
                header("Location: ./pages/home.php");
            }
            //echo $user;
            else
            {
                echo "Invalid username or password";
                header("Location: index.html");
            }
        }
    }
    if(!isset($_POST['login']))
    {
        echo "Login button not clicked";
    }
?>

I read more and more articles on this, still I can't find a solution.

Edited HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Signin for OTMS</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="signin.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <div class="container">

      <form action="login.php" method="post" class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
      </form>

    </div> <!-- /container -->


    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="assets/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>

Please help me to find what is the error. I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.

This is the error I'm getting now:

enter image description here

database name- otmsdb
table name- login
email, passowrd, 
button name- login
like image 689
dilk Avatar asked Jan 07 '23 22:01

dilk


2 Answers

Sir, your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you: Source: Udemy Online course.

EDIT: use this code, and change the variables into yours

<?php
session_start();
if(isset($_POST['login'])){
    $errmsg_arr = array();
    // configuration
    $dbhost     = "localhost";
    $dbname     = "your database name";
    $dbuser     = "your username";
    $dbpass     = "your password";
     
    // database connection
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // new data
     
    $user = $_POST['username'];
    $password = $_POST['password'];
     
    if($user == '') {
        $errmsg_arr[] = 'You must enter your Username';
    }
    if($password == '') {
        $errmsg_arr[] = 'You must enter your Password';
    }
     
    // query
    if (!$errmsg_arr) {
        $result = $conn->prepare("SELECT * FROM login WHERE username= :user");
        $result->execute(['user' => $username]);
        $row = $result->fetch(PDO::FETCH_NUM);
        if($row && password_verify($_POST['password'], $row['password']) {
            $_SESSION['user'] = $row;
            header("location: ./pages/home.php");
            exit;
        }
        else{
            $errmsg_arr[] = 'Username and Password are not found';
        }
    }
}
?>

HTML FORM:

<body>
<?php foreach($errmsg_arr as $msg): ?>
    <?=htmlspecialchars($msg, ENT_QUOTES) ?><br>
<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password"  value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>
</body>
like image 165
alim1990 Avatar answered Jan 12 '23 00:01

alim1990


Suggestions:

  1. echo mysql_error() to determine why the error is occurring:

    mysql_select_db("$db_name") or die("cannot select DB: " . mysql_error());

  2. Stop using deprecated functions " mysql_connect()", "mysql_query()" and friends. You'd be much better served with mysqli instead.

  3. Use Prepared Statements instead of building your "select" directly from your POST parameters.

like image 21
paulsm4 Avatar answered Jan 12 '23 00:01

paulsm4