-2

I have login system using MVC Pattern, though it's still procedural, and it's been 4 hours and doesn't get to work. It keeps executing the very last 'else' statement, which is redirect back to login.php. This is my code

Login Page:

<?php include 'view/template/header.php' ?>

<div class="container">
    <div class="row">
        <div class="col-lg-6 col-lg-offset-3">
            <div class="login-style">
            <h2>Silahkan Login</h2>
                <form action="controller/controller-login-admin.php" method="POST">
                <div class="form-group">
                    <label for="username">Username:</label>
                    <input type="text" name="username" class="form-control" id="username">
                </div>
                <div class="form-group">
                    <label for="pwd">Password:</label>
                    <input type="password" name="password" class="form-control" id="pwd">
                </div>
                    <button type="submit" name="submit-admin-login" class="btn btn-primary">Submit</button>
                </form> 
            </div>
        </div>
    </div>
</div>

<?php include 'view/template/footer.php' ?>

Controller

<?php 
require_once $_SERVER['DOCUMENT_ROOT']. '/project-school-frontend/admin/model/admin-model-master.php';

if (isset($_POST['submit-admin-login'])){
    $username=mysqli_real_escape_string($koneksi, $_POST['username']);
    $password=mysqli_real_escape_string($koneksi, md5($_POST['password']));
    loginUser($username, $password);
}

(Controller works fine)

Model:

<?php

require_once $_SERVER['DOCUMENT_ROOT']. '/project-school-frontend/config/database.php';

function loginUser($username, $password){

    global $koneksi;
    if (empty($username) && !empty($password)) 
        {
            $_SESSION['pesan'] = 'Userid harus diisi';
            $_SESSION['alert'] = 'info';
            header('location:../login.php');
        }
        elseif (empty($password) && !empty($username)) 
        {
            $_SESSION['pesan'] = 'Password harus diisi';
            $_SESSION['alert'] = 'info';
            header('location:../login.php');
        }
        elseif (empty($username && $password)) 
        {
            $_SESSION['pesan'] = 'Userid dan password wajib diisi';
            $_SESSION['alert'] = 'info';
            header('location:../login.php');
        }
        else
        {
            $sql= "SELECT * FROM admin WHERE username='$username' AND password='$password'";
            $query= mysqli_query($koneksi, $sql);
            $result= mysqli_num_rows($query);
            $row = mysqli_fetch_array($query);

            if($result > 0)
            {
                session_start();
                $_SESSION['username']=$row['username'];
                $_SESSION['level'] = $row['level'];
                header('Location: ../view/admin-dashboard.php');
            }
            else
            {
                header('Location: ../login.php');
            }
        }
}  

(this how it starts. The model)

What do I do?

Jixone
  • 190
  • 11
  • Try this `$query= mysqli_query($koneksi, $sql) or die(mysqli_error($koneksi));` – JYoThI Aug 14 '17 at 04:11
  • Thank you so much for replying. Much appreciated. Anyway, it doesn't work. My login page is still goin' nowhere. No message, but redirect to login page again –  Aug 14 '17 at 04:48
  • Try this `$row = mysqli_fetch_array($query); print_r($row); exit;` – JYoThI Aug 14 '17 at 04:49
  • thank you again bro for keep in touch with me but it still doesn't work. anyway this is my directory path, in case you want to know. https://pastebin.com/A3QiYvTi –  Aug 14 '17 at 06:01
  • before header all header function echo "something1"; 2,3,.. exit(); so you will find that where the page is redirecting and which if statement failing . – JYoThI Aug 14 '17 at 06:21
  • Could you give me a fiddle or something? –  Aug 14 '17 at 06:47
  • simple `if (empty($username) && !empty($password)) { $_SESSION['pesan'] = 'Userid harus diisi'; $_SESSION['alert'] = 'info'; echo 'username empty'; exit; header('location:../login.php'); }` do the same for rest of else if statement . – JYoThI Aug 14 '17 at 06:48
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Feb 08 '18 at 17:06
  • ***You really shouldn't use [MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. Make sure you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Feb 08 '18 at 17:07

1 Answers1

1

You have a few issues that I can see.

  1. This function is doing too much and needs some re-arrangement
  2. You have an error in comparison
  3. You have to bind parameters on that sql statement, it's unsafe and may be messing up the query, depending on what is being put into those fields
  4. Don't put the session_start() in an if conditional
  5. You should be using password_hash() and password_verify() (or equivalent library) for password storage and comparison

/config.php

Have a config file that contains basic stuff and always include the page on every top level page as the first thing to load

<?php
# Error reporting ON for development
error_reporting(E_ALL);
ini_set('display_errors',1);
# Define separators for full compatibility
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
# Start the session by default
session_start();
# Add the database
require_once(ROOT_DIR.DS.'project-school-frontend'.DS.'config'.DS.'database.php');

/functions/setError.php

Create a function that will do this part, that way you can reuse it.

<?php
function setError($pesan,$alert,$redirect = false)
    {
        $_SESSION['pesan'] = $pesan;
        $_SESSION['alert'] = $alert;
        # Redirect if set
        if($redirect) {
            header("Location: {$redirect}");
            exit;
        }
    }

/functions/loginUser.php

I would not use a global for your connection, instead feed the connection in using a parameter in the function.

<?php
function loginUser($koneksi, $username, $password){
    # Add messaging error
    include_once(FUNCTIONS.DS.'setError.php');
    # Trim out values
    $username = (!empty($username))? trim($username) : false;
    $password = (!empty($password))? trim($password) : false;
    # First check if either value is empty
    if(empty($username) || empty($password)) {
        # If both empty, set message
        if(empty($username) && empty($password))
            $msg = 'Userid dan password wajib diisi';
        # If username empty, set message
        elseif(empty($username))
            $msg = 'Userid harus diisi';
        # If password empty, set message
        elseif(empty($password))
            $msg = 'Password harus diisi';
        # If something is really wrong, make unknown
        else
            $msg = 'Unknown error';
        # Set session values, redirec
        setError($msg,'info','../login.php');
    }
    else {
        # Fetching the user from DB should be a function like getAdmin($koneksi,$username,$password)
        # !***** BIND PARAMETERS HERE, THIS IS UNSAFE!!! ******!
        $sql= "SELECT * FROM admin WHERE username='$username' AND password='$password'";
        $query= mysqli_query($koneksi, $sql);
        $result= mysqli_num_rows($query);
        $row = mysqli_fetch_array($query);

        if($result > 0){
            $_SESSION['username'] = $row['username'];
            $_SESSION['level']    = $row['level'];
            header('Location: ../view/admin-dashboard.php');
            exit;
        }
        else{
            setError('Invalid Username or Password','info','../login.php');
        }
    }
}  
Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • Thank you so much for your huge support. I know it would be spaghetti code. This is just an 'early stage' development. I was about to refactor it but you've come to save the day in the first place. Thanks bro. Gonna try –  Aug 14 '17 at 14:43
  • Don't forget the SQL Injection bit. – Jay Blanchard Feb 08 '18 at 17:08