How can PHP be used to create dynamic contact forms on websites?
To create dynamic contact forms on websites using PHP, you can use HTML form elements to collect user input and PHP to process the form data and send it via email. You can use PHP's mail() function to send the form data to a specified email address. Additionally, you can use PHP to validate the form data to ensure that it is correctly formatted before sending.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'your@email.com';
$subject = 'Contact Form Submission';
$message = 'Name: ' . $name . "\r\n";
$message .= 'Email: ' . $email . "\r\n";
$message .= 'Message: ' . $message;
$headers = 'From: ' . $email;
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent successfully.';
} else {
echo 'There was a problem sending your message. Please try again.';
}
}
?>