Creating a Login and Registration Form using PHP PDO Tutorial
Zouhair Eddoubaji
Posted on May 15, 2024
Dans ce tutoriel, nous allons créer une connexion et un enregistrement PDO en utilisant PHP. PHP est un langage de script côté serveur conçu principalement pour le développement Web. PDO signifie PHP Data Objects. Il s’agit d’un moyen simple et cohérent d’accéder aux bases de données. Cela signifie que les développeurs peuvent écrire du code portable beaucoup plus facilement. Il est principalement utilisé par les nouveaux codeurs pour son environnement convivial.
si vous voulez le code source(HTML/CSS) de 2 formulaires
//login form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body{
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: url(image4.jpg) no-repeat;
background-size: cover;
background-position: center;
}
.wrapper{
width: 420px;
background: transparent;
border: 2px solid rgba(255, 255, 255, .2);
backdrop-filter: blur(20px);
box-shadow: 0 0 10px rgba(0, 0, 0, .2);
color: white;
border-radius: 10px;
padding: 30px 40px;
}
.wrapper h1{
font-size: 36px;
text-align: center;
}
.wrapper .input-box{
position: relative;
width: 100%;
height: 50px;
margin: 30px 0;
}
.input-box input{
width: 100%;
height: 100%;
background: transparent;
border: none;
outline: none;
border: 2px solid rgba(255, 255, 255, .2);
border-radius: 40px;
font-size: 16px;
color: white;
padding: 20px 45px 20px 20px;
}
.input-box input::placeholder{
color: white;
}
.input-box i{
position:absolute ;
right: 20px;
top: 50%;
transform: translateY(-50%);
font-size: 20px;
}
.wrapper .btn{
width: 100%;
height: 45px;
background: white;
border: none;
outline: none;
border-radius: 40px;
box-shadow: 0 0 10px rgba(0, 0, 0, -1);
cursor: pointer;
font-size: 16px;
color:#333 ;
font-weight: 600;
}
.wrapper .register-link{
font-size: 14.5px;
text-align: center;
margin: 20px 0 15px;
}
.register-link p a {
color: white;
text-decoration: none;
font-weight: 600;
}
.register-link p a:hover{
text-decoration: underline;
}
</style>
</head>
<body>
<div class="wrapper">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?php echo $_SESSION['message']['alert'] ?> msg"><?php echo $_SESSION['message']['text'] ?></div>
<form action="login_query.php" method="post">
<h1>Login</h1>
<div class="input-box">
<input type="text" placeholder="username" name="username" required>
<i class='bx bxs-user'></i>
</div>
<div class="input-box">
<input type="password" placeholder="password" name="password" required>
<i class='bx bxs-lock-alt' ></i>
</div>
<button type="submit" class="btn" name="login">Login</button>
<div class="register-link">
<p>Don't have an account? <a href="registration.php">Register</a></p>
</div>
</form>
</div>
</body>
</html>
//Registration form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index2.css">
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins",sans-serif;
}
body{
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #49b3f01a;
background: url(image4.jpg) no-repeat;
background-size: cover;
background-position: center;
}
.wrapper{
width: 750px;
background: rgba(255, 255, 255, .1);
border: 2px solid rgba(255, 255, 255, .2);
box-shadow: 0 0 10px rgba(0, 0, 0, .2);
backdrop-filter: blur(50px);
border-radius: 10px;
color: white;
padding: 40px 35px 55px;
margin: 0 10px;
}
.wrapper h1{
font-size: 36px;
text-align: center;
margin-bottom: 20px;
}
.wrapper .input-box{
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.input-box .input-field{
position: relative;
width: 48%;
height: 50px;
margin: 13px 0;
}
.input-box .input-field input{
width: 100%;
height: 100%;
background: transparent;
border: 2px solid #fffcfc;
outline: none;
font-size: 16px;
color: white;
border-radius: 40px;
padding: 15px 15px 15px 40px;
}
.input-box .input-field input::placeholder{
color: white;
}
.input-box .input-field i{
position: absolute;
top: 50%;
left: 15px;
transform: translateY(-50%);
font-size: 20px;
}
.wrapper label{
display: inline-block;
font-size: 14.5px;
margin: 10px 0 23px;
}
.wrapper label input{
accent-color: white;
margin-right: 5px;
}
.wrapper .btn{
width: 100%;
height: 45px;
background: white;
border: none;
outline: none;
border-radius: 40px;
box-shadow: 0 0 10px rgba(0, 0, 0, .1);
cursor: pointer;
font-size: 16px;
color: #333;
font-weight: 600;
}
.bottom{
text-align:center;
margin-top:9px
}
.bottom a{
font-weight:700;
color:white;
text-decoration:none;
margin-left:5px;
}
.bottom a:hover{
text-decoration:underline;
}
@media (max-width: 576px) {
.input-box .input-field{
width: 100%;
margin: 10px 0;
}
}
</style>
</head>
<body>
<div class="wrapper">
<form action="register_query.php" method="POST">
<h1>Registration</h1>
<div class="input-box">
<div class="input-field">
<input type="text" placeholder="firstname" name="firstname" required>
<i class='bx bx-id-card'></i>
</div>
<div class="input-field">
<input type="text" placeholder="lastname" name="lastname" required>
<i class='bx bx-id-card'></i>
</div>
</div>
<div class="input-box">
<div class="input-field">
<input type="text" placeholder="username" required name="username">
<i class='bx bxs-user'></i>
</div>
<div class="input-field">
<input type="password" placeholder="password" name="password" required>
<i class='bx bxs-lock-alt' ></i>
</div>
<div class="input-field">
<input type="password" placeholder=" confirm password" name="confirmPassword" required>
<i class='bx bxs-lock-alt' ></i>
</div>
</div>
<button type="submit" class="btn" name="register">Register</button><br>
<div class="bottom">
<span>You Have an account!</span><a href="index.php" class="btn-l">Login</a>
</div>
</form>
</div>
</body>
</html>
Avant de commencer :
Vous devez d’abord télécharger et installer XAMPP ou tout serveur local exécutant des scripts PHP. Voici le lien vers le serveur XAMPP https://www.apachefriends.org/index.html. Ensuite, ouvrez le panneau de configuration de XAMPP et démarrez Apache et MySQL. J'ai également utilisé Bootstrap pour ce tutoriel, allez sur https://getbootstrap.com/ pour télécharger.
*Création d'une base de données *
Ouvrez votre serveur Web de base de données [c.-à-d. http://localhost/phpmyadmin] puis créez-y un nom de base de données db_login.
*Création de la connexion à la base de données et des tables avec PHP *
Ouvrez votre n'importe quel type d'éditeur de texte (VSCode, etc.). Ensuite, copiez/collez simplement le code ci-dessous puis enregistrez-le sous conn.php
<?php
$dsn = "mysql:host=localhost;";
$name = "root";
$pswd = "";
try {
$pdo = new PDO($dsn, $name, $pswd);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("CREATE DATABASE IF NOT EXISTS db_login");
$stmt->execute();
$stmt = $pdo->prepare("USE db_login");
$stmt->execute();
$stmt = $pdo->prepare("CREATE TABLE IF NOT EXISTS member (
mem_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
firstname varchar(50) NOT NULL,
lastname varchar(50) NOT NULL,
username varchar(30) NOT NULL,
password varchar(12) NOT NULL
)") ;
$stmt->execute();
}
catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
index.php
Cette page est la page par défaut lors de la navigation dans l'application. Cela montre le formulaire de connexion.
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body{
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: url(image4.jpg) no-repeat;
background-size: cover;
background-position: center;
}
.wrapper{
width: 420px;
background: transparent;
border: 2px solid rgba(255, 255, 255, .2);
backdrop-filter: blur(20px);
box-shadow: 0 0 10px rgba(0, 0, 0, .2);
color: white;
border-radius: 10px;
padding: 30px 40px;
}
.wrapper h1{
font-size: 36px;
text-align: center;
}
.wrapper .input-box{
position: relative;
width: 100%;
height: 50px;
margin: 30px 0;
}
.input-box input{
width: 100%;
height: 100%;
background: transparent;
border: none;
outline: none;
border: 2px solid rgba(255, 255, 255, .2);
border-radius: 40px;
font-size: 16px;
color: white;
padding: 20px 45px 20px 20px;
}
.input-box input::placeholder{
color: white;
}
.input-box i{
position:absolute ;
right: 20px;
top: 50%;
transform: translateY(-50%);
font-size: 20px;
}
.wrapper .btn{
width: 100%;
height: 45px;
background: white;
border: none;
outline: none;
border-radius: 40px;
box-shadow: 0 0 10px rgba(0, 0, 0, -1);
cursor: pointer;
font-size: 16px;
color:#333 ;
font-weight: 600;
}
.wrapper .register-link{
font-size: 14.5px;
text-align: center;
margin: 20px 0 15px;
}
.register-link p a {
color: white;
text-decoration: none;
font-weight: 600;
}
.register-link p a:hover{
text-decoration: underline;
}
</style>
</head>
<body>
<div class="wrapper">
<?php if(isset($_SESSION['message'])): ?>
<div class="alert alert-<?php echo $_SESSION['message']['alert'] ?> msg"><?php echo $_SESSION['message']['text'] ?></div>
<script>
(function() {
// removing the message 3 seconds after the page load
setTimeout(function(){
document.querySelector('.msg').remove();
},3000)
})();
</script>
<?php
endif;
// clearing the message
unset($_SESSION['message']);
?>
<form action="login_query.php" method="post">
<h1>Login</h1>
<div class="input-box">
<input type="text" placeholder="username" name="username" required>
<i class='bx bxs-user'></i>
</div>
<!-- <div class="input-box">
<input type="email" placeholder="email" required>
<i class='bx bxs-envelope'></i>
</div> -->
<div class="input-box">
<input type="password" placeholder="password" name="password" required>
<i class='bx bxs-lock-alt' ></i>
</div>
<button type="submit" class="btn" name="login">Login</button>
<div class="register-link">
<p>Don't have an account? <a href="registration.php">Register</a></p>
</div>
</form>
</div>
</body>
</html>
registration.php
This page shows the registration form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index2.css">
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap");
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins",sans-serif;
}
body{
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #49b3f01a;
background: url(image4.jpg) no-repeat;
background-size: cover;
background-position: center;
}
.wrapper{
width: 750px;
background: rgba(255, 255, 255, .1);
border: 2px solid rgba(255, 255, 255, .2);
box-shadow: 0 0 10px rgba(0, 0, 0, .2);
backdrop-filter: blur(50px);
border-radius: 10px;
color: white;
padding: 40px 35px 55px;
margin: 0 10px;
}
.wrapper h1{
font-size: 36px;
text-align: center;
margin-bottom: 20px;
}
.wrapper .input-box{
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.input-box .input-field{
position: relative;
width: 48%;
height: 50px;
margin: 13px 0;
}
.input-box .input-field input{
width: 100%;
height: 100%;
background: transparent;
border: 2px solid #fffcfc;
outline: none;
font-size: 16px;
color: white;
border-radius: 40px;
padding: 15px 15px 15px 40px;
}
.input-box .input-field input::placeholder{
color: white;
}
.input-box .input-field i{
position: absolute;
top: 50%;
left: 15px;
transform: translateY(-50%);
font-size: 20px;
}
.wrapper label{
display: inline-block;
font-size: 14.5px;
margin: 10px 0 23px;
}
.wrapper label input{
accent-color: white;
margin-right: 5px;
}
.wrapper .btn{
width: 100%;
height: 45px;
background: white;
border: none;
outline: none;
border-radius: 40px;
box-shadow: 0 0 10px rgba(0, 0, 0, .1);
cursor: pointer;
font-size: 16px;
color: #333;
font-weight: 600;
}
.bottom{
text-align:center;
margin-top:9px
}
.bottom a{
font-weight:700;
color:white;
text-decoration:none;
margin-left:5px;
}
.bottom a:hover{
text-decoration:underline;
}
@media (max-width: 576px) {
.input-box .input-field{
width: 100%;
margin: 10px 0;
}
}
</style>
</head>
<body>
<div class="wrapper">
<form action="register_query.php" method="POST">
<h1>Registration</h1>
<div class="input-box">
<div class="input-field">
<input type="text" placeholder="firstname" name="firstname" required>
<i class='bx bx-id-card'></i>
</div>
<div class="input-field">
<input type="text" placeholder="lastname" name="lastname" required>
<i class='bx bx-id-card'></i>
</div>
</div>
<div class="input-box">
<div class="input-field">
<input type="text" placeholder="username" required name="username">
<i class='bx bxs-user'></i>
</div>
<div class="input-field">
<input type="password" placeholder="password" name="password" required>
<i class='bx bxs-lock-alt' ></i>
</div>
<div class="input-field">
<input type="password" placeholder=" confirm password" name="confirmPassword" required>
<i class='bx bxs-lock-alt' ></i>
</div>
</div>
<button type="submit" class="btn" name="register">Register</button><br>
<div class="bottom">
<span>You Have an account!</span><a href="index.php" class="btn-l">Login</a>
</div>
</form>
</div>
</body>
</html>
home.php
Ce sera la page où l'utilisateur sera redirigé après s'être connecté.
Création de la fonction principale
Ce code contient le script spécifique au traitement des requêtes dans la base de données. Ce code est composé de différentes fonctionnalités, telles que la déconnexion, la connexion et l'enregistrement. Pour ce faire, écrivez ces blocs de codes dans l'éditeur de texte et enregistrez-les en conséquence, comme indiqué ci-dessous.
register_query.php
C'est là que le code enregistre toutes les données entrées dans le serveur de base de données. PDO crée une requête, puis il rassemblera toutes les données collectées et les stockera ensuite.
<?php
session_start();
require_once 'conn.php';
if(isset($_POST['register'])){
// Input validation
$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$username = trim($_POST['username']);
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
if(empty($firstname) || empty($lastname) || empty($username) || empty($password) || empty($confirmPassword)){
echo "<script>alert('Please fill up all the required fields!')</script>";
echo "<script>window.location = 'registration.php'</script>";
exit;
}
// Password confirmation
if($password !== $confirmPassword){
echo "<script>alert('Passwords do not match!')</script>";
echo "<script>window.location = 'registration.php'</script>";
exit;
}
// Secure password handling
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Prepared statement to prevent SQL injection
try{
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `member` (firstname, lastname, username, password) VALUES (:firstname, :lastname, :username, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $hashedPassword);
$stmt->execute();
$_SESSION['message'] = array("text" => "User successfully created.", "alert" => "info");
header('location:index.php');
exit;
}catch(PDOException $e){
echo "<script>alert('An error occurred while creating the user. Please try again later.')</script>";
echo "<script>window.location = 'registration.php'</script>";
exit;
}
}
?>
login_query.php
C'est là que le code peut connecter l'utilisateur. PDO envoie une requête au serveur de base de données puis reçoit une confirmation si le compte utilisateur est valide pour accéder aux données.
<?php
session_start();
require_once 'conn.php';
if(ISSET($_POST['login'])){
if($_POST['username'] != "" || $_POST['password'] != ""){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `member` WHERE `username`=? AND `password`=? ";
$query = $pdo->prepare($sql);
$query->execute(array($username,$password));
$row = $query->rowCount();
$fetch = $query->fetch();
if($row > 0) {
$_SESSION['user'] = $fetch['mem_id'];
header("location: home.php");
} else{
echo "
<script>alert('Invalid username or password')</script>
<script>window.location = 'index.php'</script>
";
}
}else{
echo "
<script>alert('Please complete the required field!')</script>
<script>window.location = 'index.php'</script>
";
}
}
?>
logout.php
C'est là que le code peut se déconnecter du compte utilisateur. L'utilisateur sera obligé de se déconnecter lorsque le bouton de déconnexion sera cliqué.
<?php
session_start();
session_destroy();
header('location: index.php');
?>
Posted on May 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.