Set up the database:
Create a database named "example_db".
Create two tables: "users" and "sessions".
The "users" table should have columns: id (INT, primary key, auto-increment), username (VARCHAR), email (VARCHAR), password (VARCHAR).
The "sessions" table should have columns: id (INT, primary key, auto-increment), user_id (INT), token (VARCHAR), expires_at (DATETIME).
Create a file named "config.php" and add the following code:
<?php
// Database configuration
$host = 'localhost';
$dbName = 'example_db';
$username = 'your_username';
$password = 'your_password';
// Create a PDO instance
try {
$db = new PDO("mysql:host=$host;dbname=$dbName", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
Create a file named "functions.php" and add the following code:
<?php
// Include the config file
require_once 'config.php';
// Function to register a new user
function registerUser($username, $email, $password)
{
global $db;
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
try {
$stmt = $db->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->execute([$username, $email, $hashedPassword]);
return true;
} catch (PDOException $e) {
return $e->getMessage();
}
}
// Function to check if a user with a given username exists
function isUsernameTaken($username)
{
global $db;
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
$stmt->execute([$username]);
$count = $stmt->fetchColumn();
return $count > 0;
}
// Function to check if a user with a given email exists
function isEmailTaken($email)
{
global $db;
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);
$count = $stmt->fetchColumn();
return $count > 0;
}
// Function to authenticate a user
function authenticateUser($username, $password)
{
global $db;
$stmt = $db->prepare("SELECT id, password FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
return $user['id'];
}
return false;
}
// Function to create a new session for the authenticated user
function createSession($userId)
{
global $db;
$token = bin2hex(random_bytes(32));
$expiresAt = date('Y-m-d H:i:s', strtotime('+1 day'));
try {
$stmt = $db->prepare("INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)");
$stmt->execute([$userId, $token, $expiresAt]);
return $token;
} catch (PDOException $e) {
return $e->getMessage();
}
}
// Function to check if a session is valid
function isValidSession($token)
{
global $db;
$stmt = $db->prepare("SELECT COUNT(*) FROM sessions WHERE token = ? AND expires_at > NOW()");
$stmt->execute([$token]);
$count = $stmt->fetchColumn();
return $count > 0;
}
Create a file named "register.php" and add the following code:
<?php
require_once 'functions.php';
// Check if the registration form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// Validate input
if (empty($username) || empty($email) || empty($password)) {
$error = "Please fill in all the fields.";
} elseif (isUsernameTaken($username)) {
$error = "Username is already taken.";
} elseif (isEmailTaken($email)) {
$error = "Email is already taken.";
} elseif (registerUser($username, $email, $password) === true) {
$success = "Registration successful. You can now <a href='login.php'>login</a>.";
} else {
$error = "Registration failed. Please try again later.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Registration</h2>
<?php if (isset($error)) : ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<?php if (isset($success)) : ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</body>
</html>
Create a file named "login.php" and add the following code:
<?php
require_once 'functions.php';
// Check if the login form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Validate input
if (empty($username) || empty($password)) {
$error = "Please fill in all the fields.";
} else {
$userId = authenticateUser($username, $password);
if ($userId) {
$token = createSession($userId);
setcookie('session_token', $token, time() + (86400 * 30), "/"); // 30 days
header("Location: dashboard.php");
exit();
} else {
$error = "Invalid username or password.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<?php if (isset($error)) : ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
That's it! You now have a basic login and registration system using PDO and Bootstrap. You can create a "dashboard.php" file for the authenticated user's dashboard, where you can check the validity of the session using the isValidSession() function.
0 comments:
Post a Comment