Secure Registration code PHP

9 views 163 lines Secure Registration code HTML, PHP, MySql
PHP Registration code
PHP • 163 lines
/* === PHP CODE === */
<?php

session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}


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


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

if (
    empty($_POST['csrf_token']) ||
    !hash_equals(
        $_SESSION['csrf_token'],
        $_POST['csrf_token']
    )
) {
    exit('Invalid request.');
}

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$mobile = trim($_POST['mobile'] ?? '');
$address = trim($_POST['address'] ?? '');

$errors = [];

/*
|--------------------------------------------------------------------------
| Name Validation
|--------------------------------------------------------------------------
*/

if (
    empty($name) ||
    mb_strlen($name) < 2 ||
    mb_strlen($name) > 100
) {
    $errors[] = 'Invalid name.';
}

if (
    !preg_match(
        "/^[a-zA-Z\s.'-]+$/u",
        $name
    )
) {
    $errors[] = 'Name contains invalid characters.';
}

/*
|--------------------------------------------------------------------------
| Email Validation
|--------------------------------------------------------------------------
*/

if (
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {
    $errors[] = 'Invalid email.';
}

$email = strtolower($email);

/*
|--------------------------------------------------------------------------
| Mobile Validation
|--------------------------------------------------------------------------
*/

if (
    !preg_match(
        '/^[6-9][0-9]{9}$/',
        $mobile
    )
) {
    $errors[] = 'Invalid mobile number.';
}

/*
|--------------------------------------------------------------------------
| Address Validation
|--------------------------------------------------------------------------
*/

if (mb_strlen($address) > 500) {
    $errors[] = 'Address too long.';
}

if (!empty($errors)) {

    foreach ($errors as $error) {
        echo htmlspecialchars($error) . '<br>';
    }

    exit;
}

/* === HTML CODE === */
<form method="post" action="register.php">

    <input type="hidden"
           name="csrf_token"
           value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

    <input type="text"
           name="name"
           maxlength="100"
           required>

    <input type="email"
           name="email"
           maxlength="255"
           required>

    <input type="tel"
           name="mobile"
           maxlength="15"
           required>

    <textarea name="address"
              maxlength="500"></textarea>

    <button type="submit">
        Register
    </button>

</form>

/* === DATABASE SCHEMA === */
CREATE TABLE users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    mobile VARCHAR(20) NOT NULL UNIQUE,
    address TEXT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    INDEX(email),
    INDEX(mobile)
);
Raw Code • 163 lines
/* === PHP CODE === */
<?php

session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}


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


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

if (
    empty($_POST['csrf_token']) ||
    !hash_equals(
        $_SESSION['csrf_token'],
        $_POST['csrf_token']
    )
) {
    exit('Invalid request.');
}

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$mobile = trim($_POST['mobile'] ?? '');
$address = trim($_POST['address'] ?? '');

$errors = [];

/*
|--------------------------------------------------------------------------
| Name Validation
|--------------------------------------------------------------------------
*/

if (
    empty($name) ||
    mb_strlen($name) < 2 ||
    mb_strlen($name) > 100
) {
    $errors[] = 'Invalid name.';
}

if (
    !preg_match(
        "/^[a-zA-Z\s.'-]+$/u",
        $name
    )
) {
    $errors[] = 'Name contains invalid characters.';
}

/*
|--------------------------------------------------------------------------
| Email Validation
|--------------------------------------------------------------------------
*/

if (
    !filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    )
) {
    $errors[] = 'Invalid email.';
}

$email = strtolower($email);

/*
|--------------------------------------------------------------------------
| Mobile Validation
|--------------------------------------------------------------------------
*/

if (
    !preg_match(
        '/^[6-9][0-9]{9}$/',
        $mobile
    )
) {
    $errors[] = 'Invalid mobile number.';
}

/*
|--------------------------------------------------------------------------
| Address Validation
|--------------------------------------------------------------------------
*/

if (mb_strlen($address) > 500) {
    $errors[] = 'Address too long.';
}

if (!empty($errors)) {

    foreach ($errors as $error) {
        echo htmlspecialchars($error) . '<br>';
    }

    exit;
}

/* === HTML CODE === */
<form method="post" action="register.php">

    <input type="hidden"
           name="csrf_token"
           value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

    <input type="text"
           name="name"
           maxlength="100"
           required>

    <input type="email"
           name="email"
           maxlength="255"
           required>

    <input type="tel"
           name="mobile"
           maxlength="15"
           required>

    <textarea name="address"
              maxlength="500"></textarea>

    <button type="submit">
        Register
    </button>

</form>

/* === DATABASE SCHEMA === */
CREATE TABLE users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    mobile VARCHAR(20) NOT NULL UNIQUE,
    address TEXT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    INDEX(email),
    INDEX(mobile)
);
#HTML #PHP #MySql
Code copied to clipboard!