In this mini project, we'll build a Contact Form with PHP. The user fills in name, email, and message, then submits. PHP will validate the input, escape the output, and show a success message when everything checks out. If you want to make the database-saving part production-ready, you can hook it up to the db-insert lesson.
php
<?php
$name = "";
$email = "";
$message = "";
$errors = [];
$success = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");
if ($name === "") {
$errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required.";
}
if (strlen($message) < 10) {
$errors[] = "Message must be at least 10 characters.";
}
if (empty($errors)) {
$success = "Thanks! Your message is ready to be saved or sent.";
// Next step: save to database with prepared statement.
}
}
?>
<form method="post">
<input type="text" name="name" placeholder="Your name" value="<?php echo htmlspecialchars($name); ?>">
<input type="email" name="email" placeholder="Your email" value="<?php echo htmlspecialchars($email); ?>">
<textarea name="message" placeholder="Your message"><?php echo htmlspecialchars($message); ?></textarea>
<button type="submit">Send Message</button>
</form>
<?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php if ($success): ?>
<p><?php echo htmlspecialchars($success); ?></p>
<?php endif; ?>You should see
If the input is valid, a success message appears. If it's invalid, a list of errors is shown.Summary
If you can finish building this project, you can say your PHP beginner foundation is pretty solid now.