Quality control department. Making a feedback form in PHP HTML and PHP scripts for feedback

In this lesson, we will learn about the function mail(), on the example of creating feedback forms in PHP with the subsequent sending of the received data by mail.

To do this, we will create two files - format.php and mail.php. The first file will contain only a form with fields for user input. Inside the tag form- button "Send" and attribute action, which refers to the handler - mail.php, it is to it that the data from the form is accessed when the button is pressed "Send". In our example, form data is sent to a web page called "/mail.php". This page contains a script for PHP which handles the form data:


The form data is sent by the method POST(processed as $_POST). $_POST is an array of variables passed to the current script via the method POST.

Below you can see the contents of the file format.php, the fields of which are filled in by the user himself on some website. All data entry fields must have the attribute name, we prescribe the values ​​ourselves, based on logic.




Feedback form in PHP with sending by mail


Feedback form in PHP







Leave a message:
Your name:



Email:

Phone number:

Message:

The text area can contain an unlimited number of characters -->







This is how the form looks visually in the browser.

Next, write the code for the file mail.php. We come up with the names for the variables themselves. AT PHP variable starts with sign $ , followed by the name of the variable. The text value of the variable is enclosed in quotation marks. With the help of variables, the contents of the form are sent to the administrator's email, simply by substituting the form element name - value in square brackets name.

$to=" [email protected]"; // email of the recipient of the data from the form
$tema = "PHP Contact Form"; // subject of the received email
$message = "Your name: ".$_POST["name"]."
";//assign the value obtained from the form name=name to the variable
$message .= "Email: ".$_POST["email"]."
"; //obtained from the form name=email
$message .= "Phone number: ".$_POST["phone"]."
"; //obtained from the form name=phone
$message .= "Message: ".$_POST["message"]."
"; //obtained from the form name=message
$headers = "MIME-Version: 1.0" . "\r\n"; // header matches format plus newline character
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n"; // indicates the type of content being sent
mail($to, $tema, $message, $headers); //sends the values ​​of the variables to the recipient's email
?>

So the data from the array $_POST will be passed to the corresponding variables and sent to the mail using the function mail. Let's fill out our form and hit the submit button. Don't forget to include your e-mail. The letter arrived immediately.

Hello friends! I want to bring to your attention the universal script to send data from forms to email. The script is ideal for sites like Landing page, business card sites, etc. Our feedback form script stands out among the mass of other scripts on the Internet in that it has the ability to connection of an unlimited number of forms with different fields on the same page and is able to send emails to multiple recipients.

So. Let's get started. Let's start with the capabilities of the script.

  1. Connecting an unlimited number of forms on one page.
  2. Checking the correctness of filling in the fields.
  3. Notification settings.
  4. Ability to use letters for each form.
  5. Letter type - (if html tags are used)
  6. Sending to an unlimited number of addresses.
  7. Individual customization of each form.
  8. The script runs on , without reloading the page.
  9. Spam bot protection.

Initial setup.


Script works on the basis of the library, so the first thing we need to do is connect it. To do this, I recommend using Google Hosted Libraries.

Let's talk about other files in more detail:

feedback.js- main script file, responsible for AJAX form submission.
jquery.arcticmodal.js,
jquery arcticmodal.
- provide the ability to display forms in a modal window.
jquery.jgrowl.js
jquery.jgrowl.css
- allow you to display notifications on the page (blocks in the upper corner of the page).

HTML and required attributes.


A required attribute for all form elements is the attribute name=""- is necessary for the subsequent configuration of the form.
For a button (type="button"), you must specify class="feedback". I also want to draw your attention to the fact that any html tag with the “feedback” class can act as a button.

Calling a form in a modal window

To call a form in a modal window, you first need to define an action on clicking on a tag, for example, a div with the class modal_btn

Since the form should be visible only in the modal window, it must be hidden by placing it in a div with the style="display: none;" attribute, and wrapped in a couple of standard divs to style the modal window.

So we figured out the basic settings for connecting our script for sending forms to E-mail. Let's now look inside and deal with setting up fields, notifications, and everything else that is there.

Example settings for one form

Settings for all forms are stored in a file feedback\index.php
$form["form-1"] = array("fields" => array("name" => array("title" => "Name", "validate" => array("preg" => "%% ", "minlength" => "3", "maxlength" => "35",), "messages" => array("preg" => "Field [ %1$s ] may contain an error", "minlength" => "The minimum length of the field [ %1$s ] is less than the allowed length - %2$s", "maxlength" => "The maximum length of the field [ %1$s ] is greater than the allowed length - %2$s",)), "tell " => array("title" => "Phone", "validate" => array("preg" => "/^((8|\+)[\- ]?)?(\(?\d( 3)\)?[\- ]?)?[\d\- ](5,10)$/", "minlength" => "5",), "messages" => array("preg" => "The field [ %1$s ] may contain an error", "minlength" => "The minimum length of the field [ %1$s ] is less than allowed - %2$s",)))), "cfg" => array(" charset" => "utf-8", "subject" => "Subject", "title" => "Title in the body of the email", "ajax" => true, "validate" => true, "from_email" = >" [email protected]", "from_name" => "noreply", "to_email" => " [email protected], [email protected]", "to_name" => "noreply1, noreply2", "geoip" => true, "referer" => true, "type" => "html", "tpl" => true, "antispam" => "email77 ", "antispamjs" => "address77", "okay" => "Message sent - OK", "fuck" => "Message sent - ERROR", "spam" => "Spambot", "notify" => "color-modal-textbox", "usepresuf" => false)); // Next form $form["form-2"] = array("fields" => array(.....
To add settings for a new form, you need to create a new array $form[""] following the example of the $form["form-1"] array

Remember I talked about the required attribute name=""?

A mandatory attribute for all form elements is the name="" attribute - it is necessary for the subsequent configuration of the form.
So it's time to tell why he still needed.
name="" is an alphanumeric key for the array, must be unique for the array $form[""]

An example of html code for clarity

Now let's understand arrays and what they are for.

$form["form-1"] = array();
$form["form-2"] = array(); etc.
These are the main arrays for each new form, contain:

  1. "fields" => array();- An array of form element settings.
    • "name" => array();- An array of form element settings (for example input name="name" type="text") which has a number of settings.
      • "title" => "Your name"- the name of the form element, will be displayed in case of errors or in the template
      • "validate" => array();- an array that contains the validation rules for the form element
        • "preg" => "%%"- regular expression
        • "minlength" => "3"- minimum field size
        • "maxlength" => "35" - maximum size fields
        • "substr" => "35"- always trim to N characters
      • "messages" => array();- an array containing validation messages, namely:
        • "preg" => "Form element does not match regular expression"
        • "minlength" => "The minimum length of the field [ %1$s ] is less than the allowed length - %2$s"- validation error, key(preg) does not match the validation key
        • "maxlength" => "The maximum length of the field [ %1$s ] exceeds the allowed length - %2$s"- validation error, key(preg) does not match the validation key
  2. "cfg" => array();- An array of form settings.
    • "charset" => "utf-8"- encoding
    • "subject" => "Subject",- Letter subject
    • "title" => "Title in the body of the email",- Header in the body of the email
    • "ajax" => true,- this is an ajax TODO form (if not needed, put - false)
    • "validate" => true,- (true) if we want form validation on the server, replace js validation with "ajax" => true. When off (false) then you can not set the validate field settings. TODO
    • "from_email" => "myemail",- sender, specify the field name (name="myemail"), and if you do not need email from the user, then a stub [email protected]
    • "from_name" => "myname",- sender, specify the field name (name="myname"), and if you do not need a username, then the No-reply stub
    • "to_email" => " [email protected]", - recipient's email. To send to multiple addresses, separate them with commas. Example ("to_email" => " [email protected], [email protected], [email protected]",)
    • "to_name" => "noreply1",- Receiver name. When sending to multiple addresses, list the names of the recipients separated by commas. Example ("to_name" => "noreply1, noreply2, noreply3",)
    • "geop" => true,- find out the location by TODO type
    • "referer" => false,- add the URL of the page from which the form was submitted
    • "type" => "plain",- letter type - plain, html (if html tags are used)
    • "tpl" => false,- use a letter template. If true, then the template file will be connected, according to the form name (name="form-1"), from the folder and the file (feedback/tpl/form-1.tpl) will be processed, otherwise everything will be sent as is, each field on a new line
    • "antispam" => "email77",- Anti-spam, the method is based on a hidden (display:none) field, which is automatically filled in only by the robot, thereby impersonating itself.
    • "antispamjs" => "address77",- Anti-spam, the method is based on a hidden (display:none) field, initially filled in, which automatically clears javascript on page load, even a smart robot cannot foresee this, and then it is blocked.
    • "okay" => " Message to user", - A message to the user is displayed if the form is successfully submitted, you can use html tags.
    • "fuck" => "Message to user",- Message to the user, displayed when an error occurs when submitting the form, you can use html tags.
    • "spam" => "Message to user",- A message to the user, displayed if a spam robot is suspected, you can use html tags.
    • "notify" => "color-modal",- what type of notifications to show, textbox - blocks in the top corner of the page, color - color highlighting in the form, modal - modal window in the center of the page, none - disable. You can combine, for example: color-modal - errors in filling fields with highlighting, and the text status of sending in the TODO modal window
    • "usepresuf" => false- Whether a custom addition is used to the subject or to the title of the letter, in case of a small change, you can specify, for example, %%cfg.title.suffix%%, for this there must be a hidden field in the form, for more details, see the presuf() function

Setting up email templates

So. Let's now deal with the theming of our messages.
First, in order for the form to be sent in a template, you need to enable the use of a template file in the form settings - "tpl" => true,
Secondly, you need to create a template file with *.tpl extension in the folder ( feedback/tpl/), according to the form name ( name="form-1").

Example: ( feedback/tpl/form-1.tpl)

Header in the body of the email
%%name.title%% %%name.value%%
%%tell.title%% %%tell.value%%

name, tell etc. - These are the attributes (name="") of the fields that the user fills in.
title- The name of the form element, which is set in the form element settings array.
value- The value of the form element.

That's all for now, but the script is certainly not perfect, so comments and descriptions of bugs are welcome and will be fixed in future versions.

P.S. The script was developed by the team

  1. Press the download button above. The zip file contains all the code you need for the form.
  2. Unzip the file feedback-form-in-html
  3. Open the file named "handler.php"
    Look for sendEmailTo add the email addresses to receive the form submissions.
  4. Upload the whole folder to your website
  5. Open the formpage.html in your browser and test

The sections below explain the code of this form

The HTML Code

Feedback

Please provide your feedback below:

CSS Styling

The following extra CSS styling is used to make the form look better

jQuery Form submission handling

Form Validations

HTML5 validations are used. For example, the Name and Email fields have "required" validation and the email field is of input type "email".

Similarly, the message field (textarea) allows a max length of 6000 characters

using the built-in HTML5 validations has the advantage that the browser itself shows the error message.
You can customize those validations to fit your needs

Server Side Handling

Every form requires a server side script to collect the form data and do the processing like send emails, save to database etc. This form comes with a PHP script to handle the form submissions. PHP is a widely supported server side scripting platform.


This article will show you how to create a PHP contact form for your website. The script will process the data entered by the user and send the result to the email you need. We will provide an option in PHP when the feedback form will work, but an error will occur when sending the email. In this case, we will write all the entered information to a file.

So, let's get started, the first thing we do is mark up the page and write styles for it. The markup will include a regular feedback form with two inputs (phone, email) and one text area where, according to our idea, the user will enter his message. The form handler will be placed on a separate page.

Feedback form

Enter phone:

Your mail:

Your question:


Let's write the styles:

Html, body( height: 100%; margin: 0; ) html( background-color: #fff; color: #333; font: 12px/14px Verdana, Tahoma, sans-serif; cursor: default; ) #feedback-form ( background-color: #ececec; margin: 50px auto 0; text-align: center; width: 430px; padding: 15px; ) #feedback-form h2( margin-bottom: 25px; ) #feedback-form input, #feedback -form textarea( background-color: #fff; border: 1px solid #A9A9A9; padding: 1px 5px; width: 90%; ) #feedback-form input( height: 26px; ) #feedback-form textarea( height: 75px; padding-top: 5px; ) #feedback-form input( margin-top: 15px; background-color: #0B7BB5; border: 1px solid #CCCCCC; color: #FFFFFF; font-weight: bold; height: 40px; line- height: 40px; text-transform: uppercase; width: 225px; cursor: pointer; )

As a result of all these actions, the following form will be obtained:


Now it's time to tackle the server. Our script will include several parts:

  • Customization;
  • Secondary functions;
  • Processing of incoming data;
  • Message output.

All these parts, of course, are conditional, since no one bothers us to make a mess out of the code or, on the contrary, to move the key parts to other files. But I think it's better to make the handler in one file, so that it would be convenient to connect it to other projects.

Setting

In this step, we will create three variables: $my_email ( mailbox to which the data is sent), $path_log (the path to the log file) and $time_back (the time the user returns to the site).

// Specify your mailbox $my_email = " [email protected]"; // Specify where the logs will be stored $path_log = "log.txt"; // Time the user returns to the site (sec) $time_back = 3;

Secondary functions

Here we describe five functions that will simplify data processing.

Message output templates:

Function error_msg($message)( $message = "

".$message."

"; return $message; ) function success_msg($message)( $message = "

".$message."

"; return $message; )

Clearing the data that came from the form:

Function clear_data($var)( return trim(strip_tags($var)); )

Sending letter:

Function send_mail($email, $subj, $text, $from)( $headers = "From: ".$from." \r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=utf-8 \r\n"; $result = mail($email, $subj, $text, $headers); if(!$result)( return false; ) return true; )

And the last function that will check the phone and mail for the correct recording of their format.

Function check_format($data, $type)( switch($type)( case "email": $pattern = "/^*@(+(*+)*\.)++$/i"; if(preg_match( $pattern, $data))( return true; ) break; case "phone": $pattern = "/^(\+?\d+)?\s*(\(\d+\))?[\s-] *([\d-]*)$/"; if(preg_match($pattern, $data))( return true; ) break; ) return false; )

As you can see, all the functions we have written are small in size. It was possible not to take them out of the data processing aisles, but when you need to change or expand something, for example, check_format(), it will be much easier and more convenient.

Processing of incoming data

First of all, we find out from which page the user came. Then we define the variables in which our messages and the status of sending the letter will be stored.

// Get the previous page $prev_page = $_SERVER["HTTP_REFERER"]; // Our messages $msg = ""; // Email status $status_email = "";

Now, so that there are no problems with the encoding, we indicate it using the header.

Header("Content-Type: text/html; charset=utf-8");

If($_SERVER["REQUEST_METHOD"] == "POST")( if(isset($_POST["number"], $_POST["email"], $_POST["question"]))( $number = clear_data ($_POST["number"]); $email = clear_data($_POST["email"]); $question = clear_data($_POST["question"]); if(check_format($number, "phone") && check_format($email, "email") && !empty($question))( // Forming an email $e_title = "(!LANG:New message"; $e_body = "!} "; $e_body .= " "; $e_body .= "Phone: ".$number; $e_body .= "
"; $e_body .= "Email: ".$email; $e_body .= "
"; $e_body .= "Question: ".$question; $e_body .= ""; $e_body .= ""; // END Generate an email if(send_mail($my_email, $e_title, $e_body, $prev_page))( $status_email = "success"; $msg = success_msg("Thanks for your question.
We'll get back to you as soon as possible."); )else( $status_email = "error"; $msg = error_msg("An error occurred while sending the email."); ) // Write to file $str = "Time: ".date ("d-m-Y G:i:s")."\n\r"; $str .= "Phone: ".$number."\n\r"; $str .= "Email: ".$email." \n\r"; $str .= "Question: ".$question."\n\r"; $str .= "Email: ".$status_email."\n\r"; $str .= "= ========================\n\r"; file_put_contents($path_log, $str, FILE_APPEND); )else( $msg = error_msg( "Please fill out the form correctly!"); ) )else( $msg = error_msg("An error occurred!"); ) )else( exit; )

In the written code, we determine whether the form has been submitted, otherwise we close this file using the exit function. Next, we check for the presence of cells with our data in the POST array, if they come, we clean them from possible garbage. After cleaning, we check the mail and phone formats, as well as the presence of text in the question variable. Next, we form a letter, send it and write logies, where, in addition to the data, we save the status of sending the letter. So we can track the work of the mail () function and at the same time not lose data.

Message output

We just have to notify the user about a successful or “not very” completed operation and return him back to the site with the form. To do this, we use markup with PHP script inclusions.

To redirect the user back to the site, we will use the refresh meta tag, where we do PHP inserts code already created with variables. We also need to use some JavaScript to make the page a little more dynamic. We are writing a timeBack() function that will count down the seconds before redirecting.

Feedback form handler

You will be returned to the page through

That's it, the feedback form is ready.