In the context of the provided PHP code for a contact form, what improvements can be made to enhance readability and maintainability?
The provided PHP code for the contact form can be improved for readability and maintainability by separating the HTML markup from the PHP logic. This can be achieved by using heredoc syntax to define the HTML content within the PHP code, making it easier to read and modify the form layout without mixing it with PHP code.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Process form submission
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate form data
if (empty($name) || empty($email) || empty($message)) {
$error_message = "All fields are required.";
} else {
// Send the email
$to = "example@example.com";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
mail($to, $subject, $body);
$success_message = "Your message has been sent!";
}
}
// HTML form markup separated using heredoc syntax
echo <<<HTML
<form method="post" action="">
<input type="text" name="name" placeholder="Name" required><br>
<input type="email" name="email" placeholder="Email" required><br>
<textarea name="message" placeholder="Message" required></textarea><br>
<input type="submit" value="Submit">
</form>
HTML;
// Display success or error messages
if (isset($success_message)) {
echo "<p>$success_message</p>";
} elseif (isset($error_message)) {
echo "<p>$error_message</p>";
}
?>