We create a feedback form in PHP. Quality control department Calling the form in a modal window

Hello friends! I would like to present to your attention a universal script for sending data from forms to email. The script is ideal for sites like Landing Page, business card sites, etc. Our Feedback Forms script stands out among the mass of other scripts on the Internet in that it has the ability to connect an unlimited number of forms with different fields on one page and is able to send letters to several recipients.

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

  • Connect an unlimited number of forms on one page.
  • Checking that the fields are filled in correctly.
  • Setting up notifications.
  • Ability to use letters for each form.
  • Letter type - (if html tags are used)
  • Sending to an unlimited number of addresses.
  • Individual customization of each form.
  • The script runs on , without reloading the page.
  • Protection against spam bots.
  • Initial setup.
    The script works based on 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 the remaining files in more detail:

    feedback.js is the 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 name="" attribute - necessary for subsequent form customization.
    For a button (type="button") you must specify class="feedback" . I would also like 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 for clicking on any tag, for example a div with the modal_btn class
    Calling a form in a modal window $(document).ready(function() ( $(document).on("click", ".modal_btn", function())( $("#small-modal").arcticmodal(); )); ));
    Since the form should be visible only in the modal window, it needs to be hidden by placing it in a div with the style="display: none;" attribute, and also wrapped in a couple of standard divs to style the modal window.
    x

    So we have figured out the basic settings for connecting our script for sending forms to E-mail. Let's now take a look inside and figure out how to configure fields, notifications and everything else that is there.

    Example of settings for one formSettings for all forms are stored in the 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" => "Minimum field length [ %1$s ] is less than allowed - %2$s", "maxlength" => "Maximum field length [ %1$s ] is greater than allowed - %2$s",)), "tell " => array("title" => "Phone", "validate" => array("preg" => "/^((8|\+)[\- ]?)?(\(?\d( 3)\)?[\- ]?)?[\d\- ](5,10)$/", "minlength" => "5",), "messages" => array("preg" => "Field [ %1$s ] may contain an error", "minlength" => "The minimum length of field [ %1$s ] is less than the allowed length - %2$s",)),), "cfg" => array(" charset" => "utf-8", "subject" => "Subject of the email", "title" => "Heading 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" => "Spam robot", "notify" => "color-modal-textbox", "usepresuf" => false)); // Next form $form["form-2"] = array("fields" => array(.....
    To add settings for a new form, you need to follow the example of the $form["form-1"] array to create a new array $form[""]

    Remember what I said about the required name="" attribute?

    A required attribute for all form elements is the name="" attribute - necessary for subsequent form customization.
    So the time has come to tell you why it is still needed.
    name="" is the alphanumeric key for the array, must be unique for the $form[""] array

    Example html code for clarity

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

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

  • "fields" => array(); - An array of settings for form elements.
    • "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(); - array, contains form element validation rules
        • "preg" => "%%" - regular expression
        • "minlength" => "3" - minimum field size
        • "maxlength" => "35" - maximum field size
        • "substr" => "35" - always cut to N characters
      • "messages" => array(); - an array containing validation messages, namely:
        • "preg" => "The form element does not match the regular expression"
        • "minlength" => "The minimum length of the field [ %1$s ] is less than acceptable - %2$s" - validation error, key (preg) does not match the validation key
        • "maxlength" => "The maximum length of the field [ %1$s ] exceeds the permissible limit - %2$s" - validation error, key (preg) does not match the validation key
  • "cfg" => array(); - An array of form settings.
    • "charset" => "utf-8" - encoding
    • "subject" => "Subject of the letter", - Subject of the letter
    • "title" => "Title in the body of the letter", - Title in the body of the letter
    • "ajax" => true, - this is the Ajax TODO form (if not needed, set it to false)
    • "validate" => true, - (true) if we want to validate the form on the server, replaces js validation with "ajax" => true. When off (false), you don’t have to set the validate field settings. TODO
    • "from_email" => "myemail", - sender, specify the field name (name = "myemail"), and if you do not need an 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 several addresses, list them separated by commas. Example ("to_email" => " [email protected], [email protected], [email protected]",)
    • "to_name" => "noreply1", - Recipient name. When sending to multiple addresses, list the names of recipients, separated by commas. Example ("to_name" => "noreply1, noreply2, noreply3",)
    • "geoip" => true, - find out location using 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 in accordance with 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 only the robot automatically fills in, thereby giving itself away.
    • "antispamjs" => "address77", - Anti spam method is based on a hidden (display:none) field, initially filled, which automatically clears javascript when the page is loaded, even a smart robot cannot anticipate this, and then it is blocked.
    • "okay" => "Message to the user", - A message to the user is displayed if the form is successfully submitted, you can use html tags.
    • "fuck" => "Message to the user", - A message to the user, displayed when an error occurs when submitting the form, you can use html tags.
    • "spam" => "Message to user", - 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 upper corner of the page, color - color highlighting in the form, modal - modal window in the center of the page, none - disable. You can combine, example: color-modal - errors in filling fields with highlighting, and text sending status 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 f -qiu presuf()
  • Setting up letter templates So. Let's now look at the topic of our messages.
    Firstly, in order for the form to be sent in a template, in the form settings you need to enable the use of a template file - "tpl" => true ,
    Secondly, you need to create a template file with a *.tpl extension in the folder (feedback/tpl/), in accordance with the name of the form (name="form-1" ).

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

    Heading in the body of the letter
    %%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 today, but the script is certainly not perfect, so comments and descriptions of bugs are welcome and will be corrected in future versions.

    P.S. The script was developed by the team

    For the development of a web project, it is very important to receive feedback from visitors. Unfortunately, on many websites the ability to send a message to developers is either not provided at all or is associated with quite serious difficulties.

    Today we will make a simple solution to this problem. Using jQuery, PHP and the PHPMailer class, the form sends the user's proposal directly to your inbox.

    HTML

    Let's start with the HTML markup. Styles are included at the top of the document, and JavaScript files are included at the bottom. This optimizes the page loading process, so the scripts are loaded last, allowing the user to see the page content.

    demo.html

    Feedback form using PHP and jQuery | Demo for the website website Feedback

    Please include contact information if you would like a response.

    Send

    Inside body located div#feedback. It is placed at the bottom right of the window using a fixed positioning, which will be seen in the CSS section of the tutorial.

    Inside this div five colored elements are placed span. Each of them has 20% width and is offset to the left. This way they are placed exactly across the entire width. div#feedback.

    Next comes the .section container, which contains the title, text area, and button.

    CSS

    Let's move on to setting styles for the form. First, let's say a few words about what the structure of a style sheet consists of. If you look at the CSS definitions below, you'll notice that every rule starts with #feedback . This creates a similar namespace in the CSS, making it easier to add code to an existing website without conflicts.

    styles.css - Part 1

    #feedback( background-color:#9db09f; width:310px; height:330px; position:fixed; bottom:0; right:120px; margin-bottom:-270px; z-index:10000; ) #feedback .section( background :url("img/bg.png") repeat-x top left; border:1px solid #808f81; border-bottom:none; padding:10px 25px 25px; ) #feedback .color( float:left; height:4px; width:20%; overflow:hidden; ) #feedback .color-1( background-color:#d3b112;) #feedback .color-2( background-color:#12b6d3;) #feedback .color-3( background-color :#8fd317;) #feedback .color-4( background-color:#ca57df;) #feedback .color-5( background-color:#8ecbe7;) #feedback h6( background:url("img/feedback.png" ) no-repeat; height:38px; margin:5px 0 12px; text-indent:-99999px; cursor:pointer; ) #feedback textarea( background-color:#fff; border:none; color:#666666; font:13px "Lucida Sans",Arial,sans-serif; height:100px; padding:10px; width:236px; resize:none; outline:none; overflow:auto; -moz-box-shadow:4px 4px 0 #8a9b8c; -webkit -box-shadow:4px 4px 0 #8a9b8c; box-shadow:4px 4px 0 #8a9b8c; )

    The first element to be styled is div#feedback. It is assigned a fixed position and anchored to the browser window. After this comes the definition for div .section and five colored elements span. These elements differ only in the background color, which is assigned separately for each class.

    At the very bottom of the presented part of the CSS file, the rules for displaying the text area are defined.

    styles.css - Part 2

    #feedback a.submit( background:url("img/submit.png") no-repeat; border:none; display:block; height:34px; margin:20px auto 0; text-decoration:none; text-indent: -99999px; width:91px; ) #feedback a.submit:hover( background-position:left bottom; ) #feedback a.submit.working( background-position:top right !important; cursor:default; ) #feedback .message ( font-family:Corbel,Arial,sans-serif; color:#5a665b; text-shadow:1px 1px 0 #b3c2b5; margin-bottom:20px; ) #feedback .arrow( background:url("img/arrows.png ") no-repeat; float:right; width:23px; height:18px; position:relative; top:10px; ) #feedback .arrow.down( background-position:left top;) #feedback h6:hover .down( background-position:left bottom;) #feedback .arrow.up( background-position:right top;) #feedback h6:hover .up( background-position:right bottom;) #feedback .response( font-size:21px; margin-top:70px; text-align:center; text-shadow:2px 2px 0 #889889; color:#FCFCFC; display:block; )

    The second part of the style sheet defines the appearance of the submit button. Note that there are three button states, the images for which are contained in one file for the background image - submit.png. They are displayed only when necessary.

    jQuery

    The feedback form has two states - minimized and maximum. When booting, the default state is set to the minimized state at the bottom right of the screen. And jQuery takes the form to its maximum state when the user clicks on the header. This functionality is accomplished by binding an event and performing simple animations.

    script.js - Part 1

    $(document).ready(function())( // Relative URL of the submit.php script. // You will probably need to change it. var submitURL = "submit.php"; // Cache the feedback object: var feedback = $( "#feedback"); $("#feedback h6").click(function())( // Animation property values ​​are stored // in a separate object: var anim = ( mb: 0, // Bottom margin pt: 25 // Top padding); var el = $(this).find(".arrow"); if(el.hasClass("down"))( anim = ( mb: -270, pt: 10); ) // First animation moves the form up or down, and the second moves the // title so that it is aligned to the minified version feedback.stop().animate((marginBottom: anim.mb)); feedback.find(".section").stop() .animate((paddingTop:anim.pt),function())( el.toggleClass("down up"); )); ));

    To keep the code simple and clear, an anim object is created at the top, which contains the values ​​for the animation, and the operator is placed if. Depending on the existence of the class ‘ down‘ on the arrow, we expand or collapse the shape.

    Second part script.js handles AJAX work with submit.php.

    script.js - Part 2

    $("#feedback a.submit").live("click",function())( var button = $(this); var textarea = feedback.find("textarea"); // We use the working class not only for setting styles for the data submit button, // but also as a kind of lock to prevent multiple generation of the form. if(button.hasClass("working") || textarea.val().length< 5){ return false; } // Запираем форму и изменяем стиль кнопки: button.addClass("working"); $.ajax({ url: submitURL, type: "post", data: { message: textarea.val()}, complete: function(xhr){ var text = xhr.responseText; // Данная операция помогает пользователю определить ошибку: if(xhr.status == 404){ text = "Путь к скрипту submit.php неверный."; } // Прячем кнопку и область текста, после которой // мы показывали полученный ответ из submit.php button.fadeOut(); textarea.fadeOut(function(){ var span = $("",{ className: "response", html: text }) .hide() .appendTo(feedback.find(".section")) .show(); }).val(""); } }); return false; }); });

    We use jQuery's AJAX $.ajax() method to interact with submit.php. This method gives a little more control over the connection than $.get() and $.post() .

    One of the advantages of the method is the visibility of the object's properties throughout the "entire" callback function. Here we check the status of the response for compliance error 404 (page not found), and display a message to the user asking them to check the path submitURL.

    Now it's time to move on to the final part - PHP.

    PHP

    PHP processes the data sent from AJAX, validates it and sends an e-mail message to the specified address.

    submit.php

    // Here you need to enter your address $emailAddress = " [email protected]"; // Use the session to prevent flooding: session_name("quickFeedback"); session_start(); // If the last form was submitted less than 10 seconds ago, // or the user has already sent 10 messages in the last hour if($_SESSION[ "lastSubmit"] && (time() - $_SESSION["lastSubmit"]< 10 || $_SESSION["submitsLastHour"] >10))( die("Please wait a few minutes before sending the message again."); ) $_SESSION["lastSubmit"] = time(); $_SESSION["submitsLastHour"]++; require "phpmailer/class.phpmailer.php"; if(ini_get("magic_quotes_gpc"))( $_POST["message"] = stripslashes($_POST["message"]); ) if(mb_strlen($_POST["message"],"utf-8")< 5){ die("Ваше сообщение слишком короткое."); } $msg = nl2br(strip_tags($_POST["message"])); // Используем класс PHPMailer $mail = new PHPMailer(); $mail->IsMail(); // Add the recipient's address $mail->AddAddress($emailAddress); $mail->Subject = "New email from the feedback form"; $mail->MsgHTML($msg); $mail->AddReplyTo("noreply@".$_SERVER["HTTP_HOST"], "Feedback form on demo page"); $mail->SetFrom("noreply@".$_SERVER["HTTP_HOST"], "Feedback form on the demo page"); $mail->Send(); echo "Thank you!";

    We first use session management to determine how often a user has used a form submission in the last hour, and also determine the amount of time that has passed since the last submission. If less than 10 seconds have passed since the last send, or the user has already sent more than 10 messages within the last hour, an error message is displayed.

    The email is sent using the PHPMailer class. Attention! It only works with PHP5.

    Multiple Methods PHPMailer used to configure outgoing e-mail. The IsMail() method tells the class to use an internal PHP function mail(). The AddAddress() method adds the recipient's address (you can add more than one recipient with additional calls to this method). After adding the subject of the letter and text, the address for replies is indicated and the message is sent.

    Ready!

    Conclusion

    You can use this form to organize quick feedback from your site visitor. A very low barrier to submission - you just need to fill out a text field and click a button - will create a great environment for visitors to your pages to start sharing their ideas. The script is also well structured and easy to customize, which will help you use it on your website with minimal effort.

    In this lesson we will get acquainted with the mail() function, using the example of creating a feedback form in PHP and then sending the received data by email.

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


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

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




    Feedback form in PHP sent by email


    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 visually looks in the browser.

    Next we write the code for the mail.php file. We come up with our own names for the variables. In PHP, a variable starts with a $ sign and then the variable name. The text value of the variable is enclosed in quotation marks. Using variables, the contents of the form are sent to the administrator's email by simply placing the name of the form element in square brackets - the name value.

    Thus, the data from the $_POST array will be transferred to the corresponding variables and sent to mail using the mail function. Let's fill out our form and press the submit button. Don't forget to include your email. The letter arrived instantly.


    In this article you will learn how to make a feedback form in PHP 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 works, but an error occurs when sending the letter. In this case, we will write all the entered information to a file.

    So, let's get started, first of all we will mark up the page and write styles for it. The markup will include a regular feedback form with two inputs (phone, mail) and one text area, where, according to our idea, the user will enter his message. We will place the form handler 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 you will get this form:


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

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

    All these parts, of course, are conditional, since no one is stopping us from making a mess out of the code or, conversely, moving key parts to other files. But I think it’s better to make the handler in one file, so that it’s convenient to connect it to other projects.

    Settings

    At this stage, we will create three variables: $my_email (the 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 data received 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 wrote are small in size. You could leave them outside the data processing area, but when you need to change or expand something, for example check_format(), it will be much simpler and more convenient.

    Processing incoming data

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

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

    Now, to avoid 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))( // Form a letter $e_title = "New message"; $e_body = ""; $e_body .= ""; $e_body .= "Телефон: ".$number; $e_body .= "!}
    "; $e_body .= "Mail: ".$email; $e_body .= "
    "; $e_body .= "Question: ".$question; $e_body .= ""; $e_body .= ""; // END Form a letter if(send_mail($my_email, $e_title, $e_body, $prev_page)) ( $status_email = "success"; $msg = success_msg("Thank you for your question.
    We will respond 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 .= "Mail: ".$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( "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 arrived, we clear them of possible garbage. After cleaning, we check the mail and phone formats, as well as the presence of text in the question variable. Next, we generate a letter, send it and write logs, where, in addition to the data, we save the status of sending the letter. This way we can track the operation of the mail() function and at the same time not lose data.

    Message output

    All we have to do is notify the user about a successful or “not so” 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 insert PHP code with the already created variables. We'll also need to use a little JavaScript to make the page a little more dynamic. We write a function timeBack(), which will count the seconds in reverse order before the redirection.

    Continuing the topic:
    Routers

    Reading time: 5 minutes In this article we will review the 5 best pedometers for Android phones: we will identify the pros and cons of the applications. All of them can be synchronized with...