Welcome to the PHP Contact Form Project! In this tutorial, we'll learn how to create a practical contact form using PHP. By the end of this lesson, you'll have a good understanding of PHP and be able to implement it in your own projects. Let's dive in!
PHP (Hypertext Preprocessor) is a popular open-source server-side scripting language. It allows us to create dynamic web pages, build web applications, and interact with databases.
Before we begin, ensure you have the following:
Let's create a basic HTML form for users to fill out.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<label for="message">Message:</label>
<textarea name="message" id="message"></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>In this example, we've created a simple HTML form with fields for name, email, and a message. The form data is sent to contact.php when the user clicks the "Send" button.
Now, let's create the contact.php file to process the form data.
<?php
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Validate the form data
if (empty($name) || empty($email) || empty($message)) {
die("All fields are required.");
}
// Send an email using PHP's built-in mail() function
$to = "your_email@example.com";
$subject = "New contact form submission";
$headers = "From: $email";
$body = "Name: $name\nEmail: $email\nMessage:\n$message";
if (mail($to, $subject, $body, $headers)) {
echo "Your message has been sent successfully!";
} else {
echo "Sorry, there was an error sending your message.";
}
?>In this script, we collect the form data, validate it, and send an email using PHP's built-in mail() function. If the email is sent successfully, we display a message to the user.
Which PHP function is used to send emails in our script?
To test our project, open the HTML file in your browser and fill out the form. You should see the email sent message if everything is working correctly.
For better security, consider using a library like PHPMailer to send emails. It offers more features and is more secure than the built-in mail() function.
That's it for today! Now that you've learned how to create a simple contact form using PHP, you're one step closer to building your own dynamic web applications. Keep practicing, and you'll master PHP in no time!