简体   繁体   中英

Password Protection Using PHP and MySQL

I am creating a web application which includes a log in and registration feature. There are two main users, clients and the 1 admin. I have so far been successfully able to create a registration page for the clients which links to a mySQL database.

And the log in page for both clients and admins. Upon log in the client or admin will be redirected to their respective dashboard.

The problem I am now facing is that - if anyone visiting the site types in the url to the trainers dashboard they will be granted full access and admin privledges. I want a message to appear saying something like 'PLEASE LOG IN'

This is a snippet of the code I am currently using in my 'login.php' file:

   <?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
    <center><form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        <div class="form-group">
                <input type="text" name="username" id="username" class="form-control input-lg" placeholder="Username" tabindex="3">
            </div>
        <div class="form-group">
                 <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
            </div>

        <br /> <br /><input type="submit" name="submit" class="btn btn-success btn-block btn-lg" value="Login" /> </center>
    </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $tusername = $_POST['username'];
    $tpassword = $_POST['password'];

    $sql = "SELECT * from client WHERE Client_username LIKE '{$username}' AND Client_password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "<p>Invalid username/password combination</p>";
    } else {
        header('location:client_dash.html?msg=success');
    }

    $sql = "SELECT * from trainer WHERE trainer_username LIKE '{$tusername}' AND trainer_password LIKE '{$tpassword}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "<p>Invalid username/password combination</p>";
    } else {
        header('location:trainer_dash.php?msg=success');
    }
}

?>

You can do this by using the SESSION variable

Your code would be changed to..

<?php  
    ob_start();
    session_start();

    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if ($mysqli->connect_errno) {
    echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }

    $username = $_POST['username'];
    $password = $_POST['password'];

    $tusername = $_POST['username'];
    $tpassword = $_POST['password'];

    $sql = "SELECT * from client WHERE Client_username LIKE {$username}' AND Client_password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) 
    {
        echo "<p>Invalid username/password combination</p>";
    }
     else 
    {
        $_SESSION['username']=$username;
        header('location:client_dash.html?msg=success');
    }

    $sql = "SELECT * from trainer WHERE trainer_username LIKE '{$tusername}' AND trainer_password LIKE '{$tpassword}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) 
    {
        echo "<p>Invalid username/password combination</p>";
    }
     else
    {
        $_SESSION['tusername']=$tusername;
        header('location:trainer_dash.php?msg=success');
    }

}

?>

And at the dashboard you can do this if it's of client

<?php 
    ob_start();
    session_start();
    if(!isset($_SESSION['username']))
    {
        die('Please log in first');
    }
    unset($_SESSION['username']);

    */rest code*/

?>

And similarly for the dashboard of trainer

<?php 
    ob_start();
    session_start();
    if(!isset($_SESSION['tusername']))
    {
        die('Please log in first');
    }
    unset($_SESSION['tusername']);

    */rest code*/

?> 

You are unsetting the session variable because if you will not do that then it will work only for the first time, because after that your session will set permanently Therefore you have to unset them

You could use sessions

before you redirect, set a session variable (don't forget to start the session first with session_start() )

    //to make sure the session_id() is different everytime the user logs in
session_regenerate_id(); 
    //store the session_id in a variable
$_SESSION['trainer']=session_id();

And on your trainer_dash.php , start with:

session_start();
if(!isset($_SESSION['trainer'])||$_SESSION['trainer']!=session_id()){
      echo 'You shouldn't be here';
}

The answers so far work fine in that they block one specific url (or folder).

If somebody enters the link eg of a picture in one of the dashboards, the picture will be delivered by the web server because no PHP script will forbid this.

If you need a robust solution, try to separate login/authentication as a component in front of your application. If ever possible, use web server filters.

In your situation, one simple solution could be using PHP to invoke a Basic Auth authentication and to password protect the dashboards. This is explained here:

http://php.net/manual/de/features.http-auth.php

If the web server sees no valid authentication, then it will block every kind of access to every kind of file, before anything of PHP is parsed.

If you need more sophisticated solutions, there will be no way around to do some research about Apache details (maybe using rewrite rules or error pages), or try to use a finished library that is separated from your application. Here is a source of knowledge about application firewalls and principles:

https://www.owasp.org/index.php/Main_Page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM