Mysql
 sql >> Database >  >> RDS >> Mysql

Elaborazione degli utenti da nome utente a gruppo_utente

Come si effettua un semplice modulo di registrazione utente e login?

La prima cosa che dovresti considerare quando crei un portale di registrazione utenti è dove e come memorizzerai gli account utente. A questo scopo utilizzeremo il database MySQL con la seguente tabella:

CREATE TABLE IF NOT EXISTS `accounts` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `Hash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `UserType` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

In questa tabella memorizzeremo il nome utente e l'hash della password. Abbiamo anche una colonna che ci dirà il tipo di account; se è un utente normale o un amministratore.

Connessione al database

Ovviamente dobbiamo connetterci al database e avviare una sessione. Questi argomenti non rientrano nell'ambito di questa risposta. Useremo PDO per connetterci al nostro database che contiene la nostra nuova tabella.

<?php

session_start();

$pdo = new PDO('mysql:host=localhost;charset=utf8mb4;dbname=test', 'dbuser', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

Per una spiegazione più approfondita di come funziona il PDO, dai un'occhiata a questo articolo:https://phpdelusions.net/pdo

Registra la funzione

Possiamo ora creare una semplice funzione che registrerà un utente nel database. Questa funzione accetterà 3 parametri:la connessione DB, nome utente e password.

Questa funzione creerà un hash della password, quindi scarterà questa password. È un semplice esempio, ma in parole povere probabilmente vorresti aggiungere più controlli e renderlo più infallibile.

function register(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
     
    $stmt = $db->prepare('INSERT INTO accounts(Username, Hash, UserType) VALUES(?,?,?)');
    $stmt->execute([
        $username,
        $hash,
        'user' // or admin
    ]);
}

La funzione di accesso

Proprio come abbiamo fatto con la funzione di registrazione, creeremo una funzione per l'accesso. La funzione accetterà gli stessi parametri, ma invece di INSERT SELECT dal database in base al nome utente corrispondente.

Se esiste un record corrispondente nel database e la password viene verificata rispetto all'hash memorizzato, memorizziamo le informazioni sull'utente in una sessione. La sessione manterrà queste informazioni sul disco rigido e fornirà all'utente un cookie da utilizzare in caso di richieste future. Utilizzando quel cookie PHP aprirà la stessa sessione ogni volta che viene richiesta la pagina.

function login(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
     
    $stmt = $db->prepare('SELECT Id, Hash, UserType FROM accounts WHERE Username=?');
    $stmt->execute([ $username ]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['Hash'])) {
        throw new Exception('Username or password incorrect!');
    }

    $_SESSION['loggedUserId'] = $user['Id'];
    $_SESSION['UserType'] = $user['UserType'];
}

Il codice completo

Ora possiamo collegare tutto questo insieme e aggiungere alcuni moduli HTML. La parte HTML è fuori portata ma vorresti tenerla separata dalla tua logica PHP. Probabilmente in un file separato del tutto.

<?php

session_start();

$pdo = new PDO('mysql:host=localhost;charset=utf8mb4;dbname=test', 'inet', '5432', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

function register(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
     
    $stmt = $db->prepare('INSERT INTO accounts(Username, Hash, UserType) VALUES(?,?,?)');
    $stmt->execute([
        $username,
        $hash,
        'user' // or admin
    ]);
}

function login(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
     
    $stmt = $db->prepare('SELECT Id, Hash, UserType FROM accounts WHERE Username=?');
    $stmt->execute([ $username ]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['Hash'])) {
        throw new Exception('Username or password incorrect!');
    }

    $_SESSION['loggedUserId'] = $user['Id'];
    $_SESSION['UserType'] = $user['UserType'];
}

if (isset($_POST['register'])) {
    register($pdo, $_POST['username'], $_POST['password']);
}

if (isset($_POST['login'])) {
    login($pdo, $_POST['username'], $_POST['password']);
}

if (!isset($_SESSION['loggedUserId'])):
?>
<!-- Register form -->
<form  method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Register">
</form>

<!-- Login form -->
<form  method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Log in">
</form>
<?php
else:
echo 'Here be something after login. You are a '.$_SESSION['UserType'];
endif;

Questo è un esempio molto semplice di come funzionano la registrazione e l'accesso in PHP. Non consiglierei di usarlo così com'è su un sito live, ma per scopi di apprendimento dovrebbe dimostrare come funziona questa funzionalità.

Puoi costruirci sopra e fare qualcosa quando il tipo di utente è diverso. Mostra più contenuti a utenti più privilegiati.