Overview
PDO registration and login helpers using password_hash and password_verify.
What this script does
This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.
Source code
<?php
declare(strict_types=1);
function registerUser(PDO $pdo, string $email, string $password): int {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 12) {
throw new InvalidArgumentException('Check email and password length.');
}
$stmt = $pdo->prepare('INSERT INTO users (email, password_hash, created_at) VALUES (:email, :hash, NOW())');
$stmt->execute(['email' => mb_strtolower($email), 'hash' => password_hash($password, PASSWORD_DEFAULT)]);
return (int)$pdo->lastInsertId();
}
function verifyLogin(PDO $pdo, string $email, string $password): ?array {
$stmt = $pdo->prepare('SELECT id,email,password_hash FROM users WHERE email=:email LIMIT 1');
$stmt->execute(['email' => mb_strtolower(trim($email))]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user || !password_verify($password, $user['password_hash'])) return null;
unset($user['password_hash']);
return $user;
}
Download starter source: Download PHP Login and Registration Starter source
Installation and customization
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- Test valid, invalid and boundary inputs before deployment.
> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.