Autore: Fabio Di Matteo
Ultima revisione: 19/06/2023 - 10:20
Lo script per le autenticazioni degli utenti in 2 versioni. La versione con base dati su array php e la versione con database Postgresql(applicabile anche ad altri). La logica dello script è che per proteggere la pagina web basta includere tra i tag :
<?php include('ca.php');?>
per la versione con utenti su array e
<?php include('cadb.php');?>
per la versine con base dati PDO.
Il controllo sui campi username e password viene affidato alle funzioni:
function checkUsername($username) function checkPassword($password)
quindi modificare secondo le prprie esigenze. Di default fanno sì che vengano accettati solo valori alfanumerici senza spazi.
La pagina da visualizzare solo se autenticati.
index.php
<!DOCTYPE html > <html > <head> <title></title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <body> <?php include('ca.php');?> <div style="border: 1px solid #008000;font-size:36px">Ciao <?php echo $_SESSION["username"] ?> sei loggato/a con successo!</div> <div style="border: 1px solid #008000;font-size:36px">Fai il <a href="logout.php">Logout</a></div> </body> </html>
ca.php
<?php // Users // make the password with: echo -n 'mypassword' |md5sum $accounts['fabio'] = 'a53bd0415947807bcb95ceec535820ee'; $accounts['rita'] = '2794d223f90059c9f705c73a99384085'; $login_error='<h2>Login error</h2><script>window.location = "index.php"; </script>'; $htmlFormLogin=''; function checkAuth($user, $pass) { global $accounts; if (array_key_exists($user, $accounts) && $accounts[$user]==$pass) { return true; }else{ return false; } } function checkUsername($username) { if (ctype_alnum($username)) { return true; }else{ return false; } } function checkPassword($password) { if (ctype_alnum($password)) { return true; }else{ return false; } } // Not edit session_start(); if (isset($_POST["login_btn"])) { if (!checkUsername($_POST["username"]) || !checkPassword($_POST["password"])) { echo "<p>Error...</p>"; die(); } $username=filter_var($_POST["username"], FILTER_SANITIZE_STRING); $password=filter_var(md5($_POST["password"]), FILTER_SANITIZE_STRING); if (checkAuth($username,$password)) { //login $_SESSION["username"]=$username; $_SESSION["password"]=$password; return; }else{ //login error echo $login_error; die(); } }else{ if (isset($_SESSION["username"])) { if (checkAuth($_SESSION["username"],$_SESSION["password"])) return ; } if (!empty($htmlFormLogin)) { echo $htmlFormLogin; }else{ echo ' <!DOCTYPE html > <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Login</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <body> <h2>Login</h2> <form action="'.$_SERVER['REQUEST_URI'].'" method="post"> <div><label> Username: <input id="username" name="username" type="text" placeholder="Insert username"></label></div> <div><label> Password: <input id="password" name="password" type="text" placeholder="Insert password"></label></div> <div><button id="login_btn" name="login_btn" >Login</button></div> </form> </body>'; } die(); } ?>
logout.php
<?php session_start(); session_destroy(); echo '<h2>Logout...</h2><script>window.location = "index.php"; </script>'; ?>
La base dati da preparare è simile per struttura alla seguente:
CREATE TABLE public.users ( id INTEGER NOT NULL, username CHARACTER VARYING(20), password CHARACTER VARYING(40), active CHARACTER VARYING(1), email CHARACTER VARYING(25) NOT NULL );
<?php // Users // make the password with: echo -n 'mypassword' |md5sum $login_error='<h2>Login error</h2><script>window.location = "index.php"; </script>'; $htmlFormLogin=''; $dsn='pgsql:host=localhost;port=5432;dbname=myaccounts;user=mydbuser;password=secret'; $table='users'; $userField="username"; $passField="password"; $activeField="active"; $sql="select * from $table where $userField = :USER and $passField = :PASS and $activeField = '1' ;"; function checkAuth($user, $pass) { global $dsn, $table, $userField, $passField, $activeField, $sql; $c=0; try { $dbh = new PDO($dsn); $stmt = $dbh->prepare($sql); $stmt->bindParam(":USER", $user); $stmt->bindParam(":PASS", $pass); if (! $stmt->execute() ) echo '<p>Error in query .</p>'; while ($row = $stmt->fetch(PDO::FETCH_BOUND)) $c++; if ($c!=0) { return true; }else{ return false; } $dbh = null; } catch (PDOException $e) { print "Error : " . $e->getMessage() . "<br/>"; die(); } } function checkUsername($username) { if (ctype_alnum($username)) { return true; }else{ return false; } } function checkPassword($password) { if (ctype_alnum($password)) { return true; }else{ return false; } } // Not edit session_start(); if (isset($_POST["login_btn"])) { if (!checkUsername($_POST["username"]) || !checkPassword($_POST["password"])) { echo "<p>Error...</p>"; die(); } $username=filter_var($_POST["username"], FILTER_SANITIZE_STRING); $password=filter_var(md5($_POST["password"]), FILTER_SANITIZE_STRING); if (checkAuth($username,$password)) { //logged in $_SESSION["username"]=$username; $_SESSION["password"]=$password; return; }else{ //login error echo $login_error; die(); } }else{ if (isset($_SESSION["username"])) { if (checkAuth($_SESSION["username"],$_SESSION["password"])) return ; } if (!empty($htmlFormLogin)) { echo $htmlFormLogin; }else{ echo ' <!DOCTYPE html > <html > <head> <title>Login</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <body> <h2>Login</h2> <form action="'.$_SERVER['REQUEST_URI'].'" method="post"> <div><label> Username: <input id="username" name="username" type="text" placeholder="Insert username"></label></div> <div><label> Password: <input id="password" name="password" type="text" placeholder="Insert password"></label></div> <div><button id="login_btn" name="login_btn" >Login</button></div> </form> </body>'; } die(); } ?>