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...
-
How to Upload Files to a Server Using PHP
Uploading files to a website is a common task. Consider uploading files to a PHP server using the POST method. This will require a form with the "file" field type and an ...
-
Iterating Elements of Array without Loops
The examples are very abstract because there are cycles. Our condition will be as follows. It is necessary to select all elements of the array by a given attribute. Or, t...
Leave a Reply