Search code examples
phpauthenticationsessionflat-file

How do I verify credentials through a text file instead of through the authorization file?


I have a PHP login script with a basic form, it leads to this file which is the authorization file that contains the credentials, but I want this file to check a text file for a matching username and password from a text file formatted like username:password or something similar. Anyone got any ideas?

<?php

if ( ! isset( $_POST['submitted'] ) )
header('Location: ' . $_SERVER['HTTP_REFERER']);

$credentials = [
   'username' => 'TESTUSER',
   'password' => 'TESTPASS'
];

if ( $credentials['username'] !== $_POST['username'] 
      OR $credentials['password'] !== $_POST['password'] )
{    
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit();
}
session_start();
$_SESSION["000000"] = "1"; 
header('Location:' . 'index.php');
exit();

Solution

  • The choice of the type of persistent storage is up to you, but you should:

    Never store passwords as plain text, use password_hash() before storing them.

    Then, on login, use password_verify() to verify that the password matches the hash in your storage medium (e.g. database / flat file).

    Example:

    <?php
    echo password_hash("somepassword", PASSWORD_DEFAULT);
    
    $hash = '$2y$10$f.iC/tadtwSws25fW2zRg./.xlY.mRK82Ys9M4acbPU/b614vA1vy';
    
    if (password_verify('somepassword', $hash)) {
        echo 'The password is valid!';
    } else {
        echo 'The password is not valid';
    }
    

    You can play around with this demo

    UPDATE: A bare bones example of a flat file (.json) user store / login-verify script. You still need to do data validation and sanitization on the user input, and decide if a flat file store is the best solution / sufficient for the level of security your application requires.

    There are two files:

    1. index.php the app - user store / login-verification
    2. users.json the flat file database (user credentials: name and password)

    index.php renders two forms, the first can be used to add users to users.json, and the second to do login verification.

    index.php

    <?php
    function getForm(string $submitName, string $submitValue)
    {
        $form = <<<HEREDOC
        <form method="POST">
        <label for="username">User Name : </label>
        <input type="text" name="username" id="username" required>
        <label for="password">Password : </label>
        <input type="text" name="password" id="password" required>
        <input type="submit" name="$submitName" value="$submitValue">
        </form>
    HEREDOC;
        return $form;
    }
    // build forms
    $userForm = getForm('submit_user', 'Add User');
    $loginForm = getForm('submit_login', 'Login');
    
    /* add a new user to flat file database */
    echo $userForm;
    if (isset($_POST['submit_user'])) {
        // retrieve user input - you still need to do data validation and sanitizing
        $userName = (isset($_POST['username'])) ? $_POST['username'] : null;
        $passWord = (isset($_POST['password'])) ? $_POST['password'] : null;
        $passWord = password_hash($passWord, PASSWORD_DEFAULT); // store a hash
        // get user.json file
        $file = "./users.json";
        $users = json_decode(file_get_contents($file), true);
        // insert new user credentials
        $users['users'][] = ['name' => $userName, 'password' => $passWord];
        // write  to flat file database
        file_put_contents($file, json_encode($users));
    }
    /* login - verify user credentials */
    echo $loginForm;
    if (isset($_POST['submit_login'])) {
        // retrieve user input - you still need to do data validation and sanitizing
        $userName = (isset($_POST['username'])) ? $_POST['username'] : null;
        $passWord = (isset($_POST['password'])) ? $_POST['password'] : null;
    
        // get user.json file
        $file = "./users.json";
        $users = json_decode(file_get_contents($file), true);
    
        // verify user
        foreach ($users['users'] as $key => $value) {
            if (strtolower($value['name']) === strtolower($userName)) {
                $hash = $value['password'];
                $verify = password_verify($passWord, $hash); // verify
                if ($verify === true) {
                    echo 'User Login Validated';
                } else echo 'Login Not Valid';
            }
        }
    }
    

    The flat file users database: users.json

    {
      "users": [
        {
          "name": "Jack",
          "password": "$2y$10$FBLkEDGX3I6HAVgptJ6q1ujo5K6cFtZn2wNKXKUhoWGNtcwfsRlpi"
        },
        {
          "name": "Jill",
          "password": "$2y$10$yKp79.HujKW3yFvxPDYvqePcUJ9uLWJ92d5TpSy62YtuRTezWrsna"
        },
        {
          "name": "Annie",
          "password": "$2y$10$eWctVmNAadkf138J0iTVr.5u7vmRl9vcglAhSEjbp0WqQphKFjwYC"
        }
      ]
    }