Sending form data to email

PHP
08.04.19

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 related to any CMS and can be used anywhere.

Code:

<?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 the letter to This email address is being protected from spambots. You need JavaScript enabled to view it.. The sender is This email address is being protected from spambots. You need JavaScript enabled to view it.. The value "from" it is desirable to specify the mailbox from the current domain. The data is written to the mail.txt file. The fields in the form were set as required using the required attribute. The spam field will provide protection against spam bots. Handler of the form at the current address. We display a message of thanks after successful sending

blog comments powered by Disqus