Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Authentication {
- private $dbHost = '127.0.0.1';
- private $dbUser = 'root';
- private $dbPassword = '';
- private $dbName = 'crawl';
- private $dbTable = 'usr';
- private $connection = null;
- public function __construct() {
- if ($this->connection === null) {
- try {
- $this->connection = new mysqli($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbName);
- } catch (Exception $e) {
- error_log($e->getMessage());
- }
- }
- if (session_status() === PHP_SESSION_NONE) {
- session_start();
- }
- }
- public function register($username, $password): bool {
- if ($this->findByUsername($username) === null) {
- if ($stmt = $this->connection->prepare("INSERT INTO " . $this->dbTable . " (username, password) VALUES (?, ?)")) {
- $hash = password_hash($password, PASSWORD_DEFAULT);
- $stmt->bind_param("ss", $username, $hash);
- $stmt->execute();
- return $stmt->affected_rows === 1 ? true : false;
- }
- }
- return false;
- }
- public function unregister($username): bool {
- if ($this->findByUsername($username) !== null) {
- if ($stmt = $this->connection->prepare("DELETE FROM " . $this->dbTable . " WHERE username = ?")) {
- $stmt->bind_param("s", $username);
- $stmt->execute();
- return $stmt->affected_rows === 1 ? true : false;
- }
- }
- return false;
- }
- public function login($username, $password): bool {
- if ($stmt = $this->connection->prepare("SELECT password FROM " . $this->dbTable . " WHERE username = ? LIMIT 1")) {
- $stmt->bind_param("s", $username);
- $stmt->execute();
- $stmt->bind_result($hash);
- $stmt->store_result();
- $stmt->fetch();
- if ($stmt->num_rows === 1) {
- if (password_verify($password, $hash)) {
- $_SESSION['username'] = $username;
- }
- }
- }
- return false;
- }
- public function logout(): void {
- unset($_SESSION['username']);
- }
- public function isAuthed(): bool {
- if (array_key_exists('username', $_SESSION) && $_SESSION['username'] !== null) {
- return true;
- } else {
- return false;
- }
- }
- public function getCurrentUser(): ?array {
- if ($this->isAuthed()) {
- return $this->findByUsername($_SESSION['username']);
- }
- return null;
- }
- public function findByUsername($username): ?array {
- if ($stmt = $this->connection->prepare("SELECT id, username FROM " . $this->dbTable . " WHERE username = ? LIMIT 1")) {
- $stmt->bind_param("s", $username);
- $stmt->execute();
- $stmt->bind_result($id, $found);
- $stmt->store_result();
- $stmt->fetch();
- if ($stmt->num_rows === 1) {
- $a = ['id' => $id, 'username' => $found];
- return $a;
- }
- }
- return null;
- }
- }
- $a = new Authentication();
- var_dump($a->unregister("test2"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement