Random Bright, Funny, Info, Deep Thoughts, AI Chats, and More

This is a standard, secure, “all-in-one” PHP form script. It includes the HTML frontend, the PHP backend logic, and essential security measures (sanitization and validation) in a single file.
You can save this file as form.php and run it on your server.
The Complete Script (form.php)
<?php
// Initialize variables to hold input values and error messages
$name = $email = $message = “”;
$nameErr = $emailErr = $messageErr = “”;
$successMsg = “”;

// Check if the form was submitted via POST
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

    // — 1. Sanitize and Validate Name —
    if (empty($_POST[“name”])) {
        $nameErr = “Name is required”;
    } else {
        $name = clean_input($_POST[“name”]);
        // Check if name only contains letters and whitespace
        if (!preg_match(“/^[a-zA-Z-‘ ]*$/”, $name)) {
            $nameErr = “Only letters and white space allowed”;
        }
    }

    // — 2. Sanitize and Validate Email —
    if (empty($_POST[“email”])) {
        $emailErr = “Email is required”;
    } else {
        $email = clean_input($_POST[“email”]);
        // Check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = “Invalid email format”;
        }
    }

    // — 3. Sanitize Message —
    if (empty($_POST[“message”])) {
        $messageErr = “Message is required”;
    } else {
        $message = clean_input($_POST[“message”]);
    }

    // — 4. Success Logic —
    // If there are no errors, proceed (e.g., send email or save to DB)
    if (empty($nameErr) && empty($emailErr) && empty($messageErr)) {
       
        // TODO: Add your email sending or database logic here
        // mail($to, $subject, $message, $headers);
       
        $successMsg = “Success! Thank you, $name.”;
       
        // Optional: Clear form values after success
        $name = $email = $message = “”;
    }
}

// Helper function to sanitize data
function clean_input($data) {
    $data = trim($data);            // Remove extra spaces, tabs, newlines
    $data = stripslashes($data);    // Remove backslashes
    $data = htmlspecialchars($data);// Convert special chars to HTML entities (Prevents XSS)
    return $data;
}
?>

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>Secure PHP Form</title>
    <style>
        body { font-family: sans-serif; padding: 20px; max-width: 500px; margin: 0 auto; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea { width: 100%; padding: 8px; box-sizing: border-box; }
        .error { color: red; font-size: 0.9em; }
        .success { color: green; background: #e6fffa; padding: 10px; border: 1px solid green; margin-bottom: 20px; }
        button { background: #007BFF; color: white; padding: 10px 15px; border: none; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>

    <h2>Contact Us</h2>

    <?php if ($successMsg): ?>
        <div class=”success”><?php echo $successMsg; ?></div>
    <?php endif; ?>

    <form method=”POST” action=””>
       
        <div class=”form-group”>
            <label for=”name”>Name:</label>
            <input type=”text” name=”name” id=”name” value=”<?php echo htmlspecialchars($name); ?>”>
            <span class=”error”><?php echo $nameErr;?></span>
        </div>

        <div class=”form-group”>
            <label for=”email”>Email:</label>
            <input type=”text” name=”email” id=”email” value=”<?php echo htmlspecialchars($email); ?>”>
            <span class=”error”><?php echo $emailErr;?></span>
        </div>

        <div class=”form-group”>
            <label for=”message”>Message:</label>
            <textarea name=”message” id=”message” rows=”5″><?php echo htmlspecialchars($message); ?></textarea>
            <span class=”error”><?php echo $messageErr;?></span>
        </div>

        <button type=”submit”>Submit</button>

    </form>

</body>
</html>

Key Features Explained
1. Security (Sanitization & Validation)
The most important part of a PHP form is ensuring the user doesn’t hack your site.
* htmlspecialchars(): This is critical. It converts characters like < and > into HTML entities. Without this, a user could type a JavaScript script into the “Name” field (Cross-Site Scripting/XSS), and your browser would execute it.
* trim(): Removes accidental whitespace before or after the input.
* filter_var(…, FILTER_VALIDATE_EMAIL): A built-in PHP function to strictly check if the email follows a valid format (e.g., user@domain.com).
2. Sticky Forms
Notice the input values: value=”<?php echo htmlspecialchars($name); ?>”
If the user types their name but forgets their email, the page will reload to show the error. Because we echo the variable back into the value attribute, the user doesn’t have to re-type their name.
3. Single File Architecture
We use action=”” in the form tag. This submits the data to the same page. The PHP at the top checks if ($_SERVER[“REQUEST_METHOD”] == “POST”).
* If you just load the page, that code is skipped.
* If you click submit, that code runs first, checks errors, and then displays the HTML with either success or error messages.
Next Steps
Now that you have the input securely caught in variables ($name, $email, $message), what do you want to do with the data?
* Send an Email: Use the PHP mail() function or a library like PHPMailer.
* Save to Database: Insert the data into a MySQL/MariaDB database.
* Log to File: Save the inputs to a .txt or .csv file on the server.
Would you like to see how to connect this to a MySQL database to save the submissions?


Discover more from NathanLegakis.com

Subscribe to get the latest posts sent to your email.

Leave a comment