Here's an example of PHP code for a contact form that sends an email:
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate inputs
$errors = [];
if (empty($name)) {
$errors[] = "Name is required";
}
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if (empty($message)) {
$errors[] = "Message is required";
}
// If there are no errors, send the email
if (empty($errors)) {
// Set the recipient email address
$to = "your-email@example.com";
// Set the email subject
$subject = "New Contact Form Submission";
// Set the email headers
$headers = "From: $name <$email>" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8" . "\r\n";
// Compose the email body
$emailBody = "Name: $name\n";
$emailBody .= "Email: $email\n\n";
$emailBody .= "Message:\n$message";
// Send the email
if (mail($to, $subject, $emailBody, $headers)) {
echo "Email sent successfully!";
exit;
} else {
echo "Error sending email. Please try again later.";
exit;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>Contact Form</h1>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="<?php echo isset($name) ? $name : ''; ?>">
<br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" value="<?php echo isset($email) ? $email : ''; ?>">
<br>
<label for="message">Message:</label>
<textarea name="message" id="message"><?php echo isset($message) ? $message : ''; ?></textarea>
<br>
<input type="submit" value="Send">
</form>
</body>
</html>
In this example, we have a simple contact form with three fields: Name, Email, and Message. When the form is submitted, the PHP code validates the inputs and checks for any errors. If there are no errors, it sends an email using the mail() function.
Make sure to replace "your-email@example.com" with the actual recipient email address where you want
Copy Rights Digi Sphere Hub
No comments:
Post a Comment