connexion utilistateur sans base de donnée
Installation
fichiers utilisés pour réaliser la connexion :
create-user.php
register.php
login.class.php
login.php
logout.php
secret.php
les Fichiers
Configuration
Configuration de l'authentification
create-user.php
$pw = 'the user provided password';
$user = array(
'pw' => password_hash($pw, PASSWORD_DEFAULT)
);
// Save user to a flat JSON file
file_put_contents('data.json', json_encode($user));
username = trim($this->username); $this->username = filter_var($username, FILTER_SANITIZE_STRING); $this->raw_password = filter_var(trim($password), FILTER_SANITIZE_STRING); $this->encrypted_password = password_hash($this->raw_password, PASSWORD_DEFAULT); $this->stored_users = json_decode(file_get_contents($this->storage), true); $this->new_user = [ "username" => $this->username, "password" => $this->encrypted_password, ]; if($this->checkFieldValues()){ $this->insertUser(); } } private function checkFieldValues(){ if(empty($this->username) || empty($this->raw_password)){ $this->error = "Both fields are required."; return false; }else{ return true; } } private function usernameExists(){ foreach($this->stored_users as $user){ if($this->username == $user['username']){ $this->error = "Username already taken, please choose a different one."; return true; } } return false; } private function insertUser(){ if($this->usernameExists() == FALSE){ array_push($this->stored_users, $this->new_user); if(file_put_contents($this->storage, json_encode($this->stored_users, JSON_PRETTY_PRINT))){ return $this->success = "Your registration was successful"; }else{ return $this->error = "Something went wrong, please try again"; } } }
} // end of class username = $username; $this->password = $password; $this->stored_users = json_decode(file_get_contents($this->storage), true); $this->login(); } private function login(){ foreach ($this->stored_users as $user) { if($user['username'] == $this->username){ if(password_verify($this->password, $user['password'])){ session_start(); $_SESSION['user'] = $this->username; header("location: account.php"); exit(); } } } return $this->error = "Wrong username or password"; } }