How can arrays be utilized to securely store user data and passwords in PHP login scripts without MySQL?
Using arrays to store user data and passwords in PHP login scripts without MySQL can be done by creating an associative array where the keys are usernames and the values are hashed passwords. This allows for secure storage and retrieval of user credentials within the PHP script itself. Additionally, using functions like password_hash() and password_verify() can enhance the security of the stored passwords.
<?php
// Create an associative array to store user data
$users = [
'user1' => password_hash('password1', PASSWORD_DEFAULT),
'user2' => password_hash('password2', PASSWORD_DEFAULT),
'user3' => password_hash('password3', PASSWORD_DEFAULT)
];
// Function to verify user credentials
function verifyUser($username, $password, $users) {
if(array_key_exists($username, $users)) {
if(password_verify($password, $users[$username])) {
return true;
}
}
return false;
}
// Example of verifying user credentials
$username = 'user1';
$password = 'password1';
if(verifyUser($username, $password, $users)) {
echo 'Login successful!';
} else {
echo 'Invalid username or password.';
}
?>
Keywords
Related Questions
- Are there any best practices for securely handling FTP connections in PHP?
- What are the recommended methods for redirecting users to a login page after a session timeout occurs during an Ajax request in PHP applications?
- What are the potential pitfalls of using $_GET in PHP for processing user input?