0

I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong? ALL users (whether in the db or not) get ignored and stuck on login page.

<?php
session_start();

//create function to check login form for admin or other type of user.      
//Redirect the admin user to the welcome page.

function login()
    {
        //strip login and password using in-build htmlspecialchars function
        $value1 = htmlspecialchars($_POST['login']);
        $value2 = htmlspecialchars($_POST['password']);    

        //set variables for the db connection
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "mydb";
        $loggedin = '';

        //Create new connection to db            
        $conn = new mysqli($servername, $username, $password, $dbname);

        //Check connection and handle any error
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            header('Locatin: login.php');
        }
        else {               
            //check if super admin user exists in db      
            $sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
            $result = mysqli_query($conn,$sql);

            //check to see if query returns any rows
            if(mysql_num_rows(($result) > 0) {
                include 'welcome.php';
            }

            //check if the password and username match
            if(($username === $value1) && ($password === $value2)) {
                $_SESSION['loggedin'] = TRUE;
                echo "Hello ".$value1.", you are logged in!<br>";
            }
            //send user error message if login/username and password wrong
            else {
                echo "Incorrect username or password<br>";
                include 'login.php';
            }

            //close the db connection               
            $conn->close();
        }
?>

Login Form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>

//function to check the form
function chkForm()
    {
        //determine the number of elements in the user login form
        var intFormLen = document.forms[0].elements.length;

        //loop through the form fields to see that a value has been input
        for (var i = 0; i < intFormLen; i++) {
            if (document.forms[0].elements[i].value == "") {
                //send user an error message if login field empty
                document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
                document.forms[0].elements[i].focus();                                
                return false;
            }
        }

        //clear the form fields
        function clearWarn(fieldName)
            {
                document.getElementById(fieldName).innerHTML = "";                  
                return true;
            }

        return;
    }   
</script>
</head>
<body>
<h2>Admin Login</h2>           
<div class="phpEcho">
    <div class="formLayout">
        <form action="#" method="post" onsubmit="return chkForm();">
            <label for="login">Login:</label>
            <input type="text"name="login" onchange="return clearWarn('fieldName')">
            <div id="login" style="color:red"></div><br>
            <label for="password">Password:</label>
            <input type="password" name="password" onchange="return clearWarn('fieldName')">
            <div id="password" style="color:red"></div><br><br>
            <input type="submit" name="cmdSubmit" value="Log in">
        </form>
    </div>
</div>
</body>
</html>
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
seaellen
  • 13
  • 6
  • `$username` and `$password` are the wrong values, no? You want to check the user accounts vs db values, right?...or what does `welcome.php` have? – chris85 May 06 '16 at 01:07
  • How does the PHP script know which session is being used? Is it passed on each JQuery AJAX request? – Julie Pelletier May 06 '16 at 01:09
  • @JuliePelletier where is the jQuery? – chris85 May 06 '16 at 01:13
  • Use the `edit` link under the tags of your question. http://stackoverflow.com/posts/37062628/edit – chris85 May 06 '16 at 01:17
  • @chris85: He only mentions using JQuery for it but doesn't show that part. – Julie Pelletier May 06 '16 at 01:21
  • @seaellen: Please show us the front-end part including the JQuery calls. – Julie Pelletier May 06 '16 at 01:23
  • All this code is for the login page, and supposedly separates the user types (hah!) and redirects them (double hah!). – seaellen May 06 '16 at 01:36
  • @chris85 The username and password are correct. – seaellen May 06 '16 at 01:59
  • @JuliePelletier - PHP knows what session from the login form (way down below in the code). Also, not sure what you mean by "show us the front-end part". All the code I have for the login page is already presented. – seaellen May 06 '16 at 02:00
  • Odd question: why are you comparing the username and password with the database's username and password (opposed to the admin's username and password) ? When you `check if super admin user exists in db`, you aren't really doing that... you are only just counting how many admins with level 1 access (?) and doing nothing with the result afterwards... – Mikey May 06 '16 at 03:42
  • Your codes won't work, I think. Since I did not see the data from login form processed by the php. the chkForm() just 'return', – sfy May 06 '16 at 04:21
  • @Jacob - Thanks for your post. I see what everyone is saying. Trying to learn by example, but not using my head enough! – seaellen May 06 '16 at 23:57
  • @Mikey - Thanks for your comments. They will help. – seaellen May 06 '16 at 23:58

2 Answers2

0

You set your form action="#" and don't submit it in JavaScript.

As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.

Julie Pelletier
  • 1,740
  • 1
  • 10
  • 18
0

This script has a lot of issues that should be addressed. I will go over a couple things that may help you:

1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.

/config.php

define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();

2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.

Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):

/functions/connection.php

function connection()
    {
        // This is just a really basic connection, one could expand on this
        return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
    }

/functions/login.php

/*
** @param $username [string] by making this a param, you can manually log in users outside of POST
** @param $password [string] same as username
** @param $conn [resource] You will want to inject your connection into this
**                         in order to use it. Don't make the connection 
**                         inside. May as well reuse resources already active
** @return [bool] If you return TRUE or FALSE, that will tell your script
**                whether the login succeeded or failed for notification
*/

function login($username,$password,$conn)
    {
        // Don't worry about stripping down the username/pass, just bind
        // the username and match the password
        // You need to select from your user table (or whatever table
        // you are storing your usernames for your site)
        $query = $conn->prepare("select * from `users` where `username` = :0");
        $query->execute(array(':0'=>$username));
        $result = $query->fetch(PDO::FETCH_ASSOC);
        if(empty($result))
            return false;
        // You will want to use password_hash to save passwords
        if(!password_verify($password,$result['password']))
            return false;
        // I use htmlspecialchars here so I don't forget when echoing to page
        // but you can do it at the time you echo to browser
        $_SESSION['first_name'] = htmlspecialchars($result['first_name']);
        //etc....
        return true;
    }

To use:

/index.php

// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');

// Set connection
$con    = connection();

// See if a post has been made
if(isset($_POST['login'])) {
    $loggedin = login($_POST['login'],$_POST['password'],$con);
}

// If the login attempt made
if(isset($loggedin)) {
    // If successful
    if($loggedin) {
        header('Location: welcome.php');
        exit;
    }
    else
        // If failed, you can note in a variable an echo in the html section
        $error = 'Login failed';
}

For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33