Hugh Chalmers Hugh Chalmers - 14 days ago 8
PHP Question

Php login store passwords in txt

Now, I know that storing passwords in a text file is not secure, but don't worry. Security is not my goal here, this is like one of those hackme websites.

So, I need to know, how would I store usernames and passwords in a text file, so far I have this array

$logins = array('Example' => '123','test' => '123','simon' => '123');


and this if statement

if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:index.php");
exit;
}


How would I make it so rather than storing them as a list, I can store them in a text file, and then run the if statement, on the text file?

Answer

You can make a JSON kind of thing and refer it as an array. So, prepare the file first. The contents of passwords.json (or passwords.txt, call it whatever you want):

{}

And now, what you need to do is the following:

  • Read the contents of the file.
  • Parse them into an associative array.
  • Check the keys for existence of username.
  • Verify the password.

So, ultimately, the code would be something like:

<?php
    // Read the file.
    $users = file_get_contents("passwords.json");
    // Convert into an associative array.
    $users = json_decode($users);
    // Get the input from the user.
    $username = $_POST["username"];
    $password = $_POST["password"];
    // Check the validity.
    if (array_key_exists($username, $users) && $users[$username] == $password) {
        // Valid user.
        $_SESSION["user"] = array($username, $password);
    } else {
        echo "Not Right!";
    }
?>

And if you wanna store the users, then you just need to do the opposite.

  1. Get the username and password.
  2. Read the original list of users into an array.
  3. Append the new username and password.
  4. Convert it into JSON.
  5. Save it inside the file.

The final code:

<?php
    // Read the file.
    $users = file_get_contents("passwords.json");
    // Convert into an associative array.
    $users = json_decode($users);
    // Get the input from the user.
    $username = $_POST["username"];
    $password = $_POST["password"];
    // Store the new one into the array.
    $users[$username] = $password;
    // Convert back to JSON.
    $users = json_encode($users);
    // Put it into the file.
    file_put_contents("passwords.json", $users);
?>