How to Send HTML Form Data to Email Using PHP
Sending a form to email is an important and common way of communicating with a web resource user. Let’s write a simple form for sending data to email using the PHP mail() function. Our form will also write data to a file on the server. The code is not tied to any CMS and can be used anywhere. It is important that the mail() function is enabled on your hosting.
<?php
if(isset($_POST['spam']) && isset($_POST['submit']) && !$_POST['spam']){
//departure date
$date = date('d-m-Y H:i');
//the value from the name field is limited to 100 characters
$field_name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
//the value of the message field is limited to 1000 characters
$field_message = substr(htmlspecialchars(trim($_POST['message'])), 0, 1000);
$to = "user@example.com"; //to
$subject = "Data from the feedback form";
//text of the letter
$msg = "Name: $field_name
\nMessage: $field_message";
$headers = 'From: webmaster@example.com'; // from
mail($to, $subject, $msg, $headers);//send the letter
//create a string to write to the file on the server
$file_msg = "$date Name: $field_name; Message: $field_message;\n";
//write data to file
file_put_contents(__DIR__ . '/mail.txt', $file_msg, FILE_APPEND);
echo '<p>Thank you for your message</p>';
}
?>
<form method="post" action="">
<input type="text" name="name" placeholder="Name*" required>
<textarea name="message" placeholder="Message*" required></textarea>
<input type="hidden" name="spam" value="">
<input type="submit" value="Send" name="submit">
</form>
We send a letter to user@example.com. In the “from” value, it is desirable to specify a mailbox from the current domain. The data is written to the mail.txt file. The fields in the form were set as mandatory using the “required” attribute. The “spam” field will provide protection from spambots, but minimal. The form handler is at the current address. We display a thank-you message after successful sending.
In your implementation, you can save the data to the database instead of writing it to the file. You can also move the request handler to a separate file.
Similar posts:
-
How to Remove the "Website" Field from the WordPress Comment Form
By default, WordPress includes a "Website" or "URL" field in its comment form. While this may be useful in some cases, it often attracts spammers who leave low-quality co...
-
Fixing Image URL in ACF (Advanced Custom Fields)
The ACF (Advanced Custom Fields) plugin is a great and convenient tool for extending the functionality of Wordpress. ACF allows you to add custom fields to your project's...
-
Caching Data to a File Using PHP
Sometimes it becomes necessary to limit the number of queries to an external data source. Especially if they do not change constantly. For example, the exchange rate in t...
Leave a Reply