There are two common ways to do what You’re trying: use separate files or a single one. I’ll use the first because it’s more easy to maintain.
You will need two files: form.html and sender.php. Both files need to be on the same directory (until you learn more at least).
On the form.html you write the HTML required to create your contact form:
<form id="contact-me" method="post" action="sender.php">
<input type="text" name="sender_name" placeholder="Your name" />
<input type="text" name="sender_mail" placeholder="Your Email" />
<textarea name="sender_message" placeholder="Your message"></textarea>
<button type="submit">Send</button>
</form>
The important parts of this are:
- The form attributes
method
and action
. The method specifies which method is used to send the data to the server and the action is the URL of the server file that processes the sent data. I’ll leave it to you to investigate what other method
s are and what’s the default one if the attribute is not specified.
- For the
input
elements, each one needs to have a name, otherwise PHP won’t recognize the data.
- The button with a type of submit, which is in charge of actually sending the form to the server.
The sender.php receives the data after we click the submit button.
<?php
// sender.php
if (
isset($_POST['sender_name'])
&& isset($_POST['sender_mail'])
&& isset($_POST['sender_message'])
) { // Check if any of the fields is missing, otherwise send the mail
$name = $_POST['sender_name'];
$mail = htmlspecialchars($_POST['sender_mail']);
$message = $_POST['sender_message'];
$headers = array(
'From' => 'myweb@mydomain.com', // Replace this with an email using Your domain
'Reply-to' => $mail
);
if (mail('keith.williams@bloggoneit.net', "You have a subscription from $name <$mail>", $message, $headers)) {
// The message was sent.
echo "<p>Message sent</p>";
} else {
// Something went wrong and You'll need to look into the error logs
echo "<p style='color: red'>We failed to send the message :(</p>";
} else {
// If this message appears, then one or more fields were empty
echo "<p style='color: red'>Please fill the required information</p>";
}
I must warn You though, this is not useful for production, only for learning purposes.