pull-icon
logo-mobile

The Good, The Bad and Ugly

Home/Forums/The Good, The Bad and Ugly

EmmaS

this month

BAD vs MODERN PHP Form Handling

A simple but powerful comparison for new developers

Many beginners still learn outdated PHP examples from YouTube or old blogs.
Below is a direct side-by-side comparison showing:

Bad (old, insecure, messy)
vs
Modern PHP (secure, clean, professional)

<?php

if ($_POST['submit']) {

    $name  = $_POST['name'];
    $email = $_POST['email'];

    $conn = mysqli_connect("localhost", "root", "", "test");

    $sql = "INSERT INTO contact VALUES ('$name', '$email')";
    mysqli_query($conn, $sql);

    echo "Saved!";
}

?>
<form method="post">
    Name: <input type="text" name="name">

    Email: <input type="text" name="email">

    <input type="submit" name="submit" value="send">
</form>

What’s Wrong Here?
SQL injection risk ('$name' goes directly into the query)
No validation
No HTML escaping
No CSRF protection
mysqli without prepared statements
Hard-coded DB credentials
Logic mixed directly with HTML
No error handling
Old-style $_POST['submit'] check
root user with blank password

MODERN, SECURE, CLEAN PHP (PDO + Validation + CSRF)

<?php
declare(strict_types=1);
session_start();

// Generate CSRF token
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
}

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Modern Form</title>
</head>
<body>

<h2>Modern PHP Form Example</h2>

<?php if ($flash): ?>
<div style="background:#eef;padding:10px;margin-bottom:10px;">
    <?= h($flash) ?>
</div>
<?php endif; ?>

<form action="submit.php" method="post">
    <label>Name:</label>

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



    <label>Email:</label>

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



    <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
    <button type="submit">Send</button>
</form>

</body>
</html>


<?php
declare(strict_types=1);
session_start();

// 1. CSRF token check
if (!isset($_POST['csrf']) || $_POST['csrf'] !== ($_SESSION['csrf'] ?? '')) {
    exit("Security check failed.");
}

// 2. Validate input
$name  = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');

if ($name === '' || $email === '') {
    $_SESSION['flash'] = "All fields are required.";
    header("Location: index.php");
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['flash'] = "Invalid email.";
    header("Location: index.php");
    exit;
}

// 3. PDO connection
$pdo = new PDO(
    "mysql:host=localhost;dbname=test;charset=utf8mb4",
    "user",
    "pass",
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
);

// 4. Insert safely with prepared statements
$stmt = $pdo->prepare("
    INSERT INTO contact_form (name, email, created_at)
    VALUES (:name, :email, NOW())
");
$stmt->execute([
    ':name'  => $name,
    ':email' => $email
]);

$_SESSION['flash'] = "Form submitted!";
header("Location: index.php");
exit;


Why the Modern Version Is Better

SQL Injection Protection = Prepared Statements
Validation = Proper validation
CSRF Protection = CSRF token
HTML Escaping = XSS-safe
DB Layer = PDO (standard)
Error Handling = Exceptions
Code Structure = Logic separated
Security = Professional

Leave a Comment

You must be logged in to post a reply.


BellOnline provides fast, reliable UK hosting designed for modern radio and web projects. Optimised servers, strong security, and excellent uptime ensure your station runs smoothly.
MixStream delivers broadcast-grade radio streaming with outstanding stability, crystal-clear audio, and powerful performance even during peak listener hours. Perfect for hobby stations and professional broadcasters alike.


Your secure download link has been emailed to:

Goto BellOnline Now!