Feedback form php. We create a feedback form in PHP. Feedback form

  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.

It's no secret that very often you have to somehow communicate with visitors to your site. Of course, you can just give your e-mail(as I did), but you can offer another way - this is feedback form. Of course, this requires knowledge PHP. But so that you do not have to write everything from scratch, I provide you with a very good feedback form script.

After downloading, extract the archive to your site (look, do not delete anything from yourself). Now let's set it up. To do this, open the file config.php". And change the values ​​of the following variables:

  1. "mail to" - replace " [email protected] "your mailbox address.
  2. "charset" - set the encoding, although if your site is in Russian, you can leave " windows-1251".
  3. "content"I advise you to leave" text/plain", since it is unlikely that your visitors will send you messages in HTML format.

Now you can run the file index.php at the script. As a result, a form will appear in front of you. You can fill it out and send a letter.

Now the question arises: How to embed this feedback form on your site?". To do this, find the file that is responsible for your feedback page (let it be " feedback.html"). Immediately change the extension to php(i.e. on " feedback.php"). Copy the code from index.php script to a file feedback page (feedback.php). Now you can do whatever you want between the tags And , just do not erase what you inserted from index.php. What's between the tags And ?> don't touch it unless you know exactly what you're doing.

And, finally, if you do not like the appearance of the form, then you can correct it in the file " styling.css".

If you have any questions, or there are some glitches with the script (I have not tested it), then write to me at e-mail for me to fix.

In order not to depend on the work of other people's scripts, learn how to create them yourself. My video course will teach you this " PHP and MySQL from Zero to Guru":

The contact form can be placed on . Its simple to make. If you accept the proposed CSS style, then the form will be "rubber":

Below are two options for the mail sending script: with and without Javascript

1. Contact form without reload

  1. PHP moved to a separate file
  2. pressing F5 will not submit the form again
  3. the page will not reload after submitting the form
  4. not supported by IE8 and below (you need to add analogs to addEventListener() , preventDefault() and XMLHttpRequest or use option 2)

contacts.html file

How can I call you: Contact email: name="contactFF" required placeholder="email address" x-autocompletetype="email"> Ваше сообщение: !}

contacts.php file

[email protected]"; $subject = "Contact form filled out with ".$_SERVER["HTTP_REFERER"]; $subject = "=?utf-8?b?". base64_encode($subject) ."?="; $message = "Name : ".$_POST["nameFF"]."\nIP: ".$_SERVER["REMOTE_ADDR"]."\nMessage: ".$_POST["messageFF"]; $headers = "Content-type: text/plain ; charset="utf-8""; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Date: ". date("D, d M Y h:i:s O") . "\r\n"; mail($to, $subject, $message, $headers); echo $_POST["nameFF"]; ) ?>

2. Contact form without JavaScript

  1. in most cases the file extension should be .php
  2. when pressing F5 the form will be submitted again
  3. after submitting the form the page will be reloaded
  4. validation of fields is not performed on the server side

contacts.php file

[email protected]", "contact form filled with ".$_SERVER["HTTP_REFERER"], "Name: ".$_POST["nameFF"] ."\nEmail: ".$_POST["contactFF"]."\nMessage: ".$_POST["messageFF"]); echo("

Your message has been received, thank you!

"); } ?>
How can I call you: Contact email: name="contactFF" required placeholder="email address" x-autocompletetype="email"> Ваше сообщение: !}
  1. need to replace [email protected]
  2. need to replace contacts.php to the full address, for example, http://site.ru/folder/folder/contacts.php
  3. in order to add a new field, you need to make changes to the HTML, JavaScript and PHP code. In other words, add the same sections as for contactFF. Example as described in

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 suggestion directly to your mailbox.

HTML

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

demo.html

Contact form using PHP and jQuery | Website demo

Feedback

Please include contact information if you would like a response.

Send

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

Within this div five colored elements are placed span. Each one is 20% wide and offset to the left. Thus, they are placed exactly on the entire width. div #feedback.

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

css

Let's move on to styling 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 each rule starts with #feedback. This creates a CSS-like namespace that makes it easy 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-sha dow: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. It is followed by a 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 background image file - submit.png. They are only released when needed.

jQuery

The feedback form has two states - minimized and maximum. On load, the minimized state is set to the bottom right of the screen by default. And jQuery puts the form in the maximum state when the user clicks the mouse button on the heading. 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 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 margin ); 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 one moves // the title so it aligns with the minimized version feedback.stop().animate((marginBottom: anim.mb)); feedback.find(".section").stop() .animate((paddingTop:anim.pt),function()( el.toggleClass("down up"); )); ));

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

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 for more than just styling the submit button, // but also as a kind of padlock to prevent multiple form generations 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 the jQuery method for AJAX $.ajax() to interact with submit.php. This method gives you a bit more control over the connection than $.get() And $.post().

One of the advantages of the method is the visibility of the object's properties in the "whole" callback function. Here we check the status of the response for compliance 404 error (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 with AJAX, validates it and sends an e-mail message to the given address.

submit.php

// Enter your email address here $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 mail from the feedback form"; $mail->MsgHTML($msg); $mail->AddReplyTo(" [email protected]".$_SERVER["HTTP_HOST"], "Contact form on demo page"); $mail->SetFrom(" [email protected]".$_SERVER["HTTP_HOST"], "Contact form on 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 to determine the time elapsed since the last submission. If less than 10 seconds have passed since the last send, or if the user has already sent more than 10 messages within the last hour, an error message is displayed.

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

Multiple Methods PHPMailer used to configure outgoing e-mail. Method IsMail() tells the class to use an internal PHP function mail(). Method AddAddress() adds the address of the recipient (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 a quick feedback from a visitor to your site. A very low barrier to submission - you just need to fill out a text field and click a button - will create excellent conditions for visitors to your pages to start sharing their ideas. The script is also well structured and easy to set up, which will help you to use it on your site with minimal effort.

One of the most common tasks in practice is the implementation of a feedback form. Tobish writing its HTML code, designing it in CSS, creating a PHP script that would process the data received from the user and send it to our mail, writing a JS script that would check the form for the adequacy of the input data, protecting our offspring from spam, so that our the mailbox did not collapse from bot attacks.

All of the above points will be considered in our review and commented in detail.

So, let's start creating a feedback form:

HTML

First of all, we write HTML code, it sets the fields that the user will fill in. They will be developed in the future. The form code looks like this:

< form method= "post" action= "mail.php" > < div class = "left" > < label for = "name" >Name: < input maxlength= "30" type= "text" name= "name" /> < label for = "phone" >Telephone: < input maxlength= "30" type= "text" name= "phone" /> < label for = "mail" >Email: < input maxlength= "30" type= "text" name= "mail" /> < div class = "right" > < label for = "message" >Message: < textarea rows= "7" cols= "50" name= "message" > < input type= "submit" value= "Send" />

And visually it looks like this now:

I agree, so far everything is ugly and nothing is clear, but we have just begun.

Consider the above code in detail:

  • < form method= "post" action= "mail.php" > …


    In order to create a form, you need to use the form tag. It is he who determines the beginning and end of the form for the code interpreter. It, like any tag, has a whole set of attributes, but there are only two required for the form to work, these are method (the method of sending a request to the server, post is standardly used for forms) and action (indicates the path to the form handler file, namely in this file will contain a PHP script, which will then send the values ​​entered by the user to us by mail, in our case we see that this file is called mail.php and it lies in the same site directory as the page we are considering).
  • < input maxlength= "30" type= "text" name= "name" />


    Next we have inputs. These are actually the form fields themselves into which users will enter the information we need (type = "text" indicates that it will be text). The maxlength attribute specifies how many characters the user can enter in the given form field. The most important attribute is name - it specifies the name of a particular field. It is by these names that the PHP script will further process the information coming into it. If desired, you can also set the placeholder attribute, which displays text inside the field that disappears when the cursor is placed inside it. One problem with the placeholder is that it is not supported by some older browsers.
  • < label for = "name" >Name:


    Used if we have abandoned placeholders. The usual field label, the for attribute tells which field the given label refers to. The value indicates the name of the field of interest to us.
  • < textarea rows= "7" cols= "50" name= "message" >


    Just like the input, it is intended for the user to enter information, only this time the field is sharpened for long messages. Rows specifies the size of the field in lines, cols in characters. In general, they set the height and width of our field.
  • < input type= "submit" value= "Send" />


    Type="submit" tells us that this is a button for submitting the form, and value specifies the text that will be inside this button.
  • < div class = "right" >


    used only for further visual design of the form.

css

In order for our feedback form to look presentable, it needs to be designed. To get the following result:

We used this code:

form ( background: #f4f5f7; padding: 20px; ) form . left, form. right ( display: inline- block; vertical- align: top; width: 458px; ) form . right ( padding- left: 20px; ) label ( display: block; font- size: 18px; text- align: center; margin: 10px 0px 0px 0px; ) input, textarea ( border: 1px solid #82858D; padding: 10px; font- size: 16px; width: 436px; ) textarea ( height: 98px; margin- bottom: 32px; ) input[ type= "submit" ] ( width: 200px; float: right; border: none; background: #595B5F; color: #fff; text-transform: uppercase; )

I don’t see the point in describing CSS in detail, I’ll only draw your attention to the key points:

  1. It is not necessary to write a design for each tag in the form. Try to build your selectors in such a way that you can style all the elements you need in a couple of lines of code.
  2. Do not use extra tags by type to break lines and create indents < br>, < p> and so on, these tasks are perfectly handled by CSS with the property display: block and margin with padding. More about why you shouldn't use < br> in layout, in general, you can read the br tag in the article, but is it really needed? .
  3. Do not use tabular layout for forms. This goes against the semantics of this tag, and search engines love semantic code. In order to form the visual structure of the document, div tags are enough for us, and the display: inline-block properties set in CSS (arranges blocks in a row) and vertical-align: top (prevents them from spreading across the screen), we set them the required height and voila, nothing superfluous and everything is arranged as we need.

For those who want to save their time on the design of sites, I can advise you to use CSS frameworks when creating sites, especially self-written ones. My choice in this regard is Twitter Bootstrap. A lesson on designing forms using it can be viewed.

PHP

Well, it's time to make our form workable.

We go to our root directory of the site and create the mail.php file there, to which we previously specified the path in the action attribute of the form tag.

Ultimately, his code will look like this:

Your message has been sent successfully \" javascript: history.back()\" >Go back

" ; if (! empty ($_POST [ "name" ] ) and ! empty ($_POST [ "phone" ] ) and ! empty ($_POST [ "mail" ] ) and ! empty ($_POST [ "message" ] ) ) ( $name = trim (strip_tags ($_POST [ "name" ] ) ) ) ; $phone = trim (strip_tags ($_POST [ "phone" ] ) ) ; $mail = trim (strip_tags ($_POST [ "mail" ] ) ) ; $message = trim (strip_tags ($_POST [ "message" ] ) ) ; mail (, , "Sent to you: " . $name . "
His number: " . $phone . "
His mail: " . $mail . "
His message: "
. $message , ) ; echo "Your message has been sent successfully!
You will receive an answer shortly
$back"
; exit; ) else ( echo ; exit ; ) ?>

You can skip the discussion of the HTML and CSS parts of this document. At its core, this is a regular page of the site, which you can design as you wish and need. Let's consider the most important part of it - the PHP script for processing the form:

$back = "

\" javascript: history.back()\" >Go back

" ;

With this line we create a link to return to the previous page. Since we do not know in advance from which page the user will get to this one, this is done using a small JS function. In the future, we will simply refer to this variable to display it in the places we need.

if (! empty ($_POST [ "name" ] ) and ! empty ($_POST [ "phone" ] ) and ! empty ($_POST [ "mail" ] ) and ! empty ($_POST [ "message" ] ) ) ( // internal part of the handler) else ( echo "Please fill in all fields to send a message! $back "; exit; )

Here we fasten the form check for the fullness of the fields. As you guessed, in the $_POST["name"] part, we write the value of the name attribute of our inputs in quotes.

If all the fields are filled, then the script will start processing the data in its internal part, but if at least one field has not been filled, then a message will be displayed on the user's screen with a request to fill in all the fields of the form echo "To send a message, fill in all the fields! $back" and a link to return to the previous page that we created with the very first line.

Next, paste it into the inside of the form handler:

$name = trim (strip_tags ($_POST [ "name" ] ) ) ; $phone = trim (strip_tags ($_POST [ "phone" ] ) ) ; $mail = trim (strip_tags ($_POST [ "mail" ] ) ) ; $message = trim (strip_tags ($_POST [ "message" ] ) ) ;

Thus, we cleared the user input from html tags and extra spaces. This allows us to protect ourselves from receiving malicious code in messages sent to us.

Checks can be complicated, but it's up to you. We have already set the minimum protection on the server side. We will do the rest on the client side using JS.

I do not recommend completely abandoning form protection on the server side in favor of JS, because although it is extremely rare, there are unique people with JS disabled in the browser.

After cleaning the tags, add the message sending:

mail ( "[email protected]", "Email from your_site_address", "Wrote you: " . $name . "
His number: " . $phone . "
His mail: " . $mail . "
His message: "
. $message , "Content-type:text/html;charset=windows-1251") ;

It is this line that is engaged in the formation and sending of a message to us. It is filled in as follows:

  1. "[email protected]" - insert your mail between quotes here
  2. "Email from your_site_address" is the subject of the message that will be sent to the mail. You can write anything here.
  3. "Wrote you: ".$name." < br /> His number is: ".$phone." < br /> His mail: ".$mail." < br /> Its message: ".$message - we form the text of the message itself. $name - we insert the information filled in by the user through accessing the fields from the previous step, in quotes we describe what this field means, with the tag < br /> we do a line break so that the message as a whole is readable.
  4. Content-type:text/html;charset=windows-1251 - at the end there is an explicit indication of the data type transmitted in the message and its encoding.

IMPORTANT!

The encoding specified in the "head" of the document ( < meta http- equiv= "Content-Type" content= "text/html; charset=windows-1251" /> ), the encoding from the message Content-type:text/html;charset=windows-1251 and in general the encoding of the PHP file must match, otherwise in the messages received by mail, instead of Russian or English letters, “crazy words” will be displayed.

Many people do not explicitly indicate the encoding of the message being sent, but this may cause problems in the future on some mail clients (unreadable letters arrive in the mail), so I recommend that you specify it anyway.

Checking the form for the adequacy of the input data

So that users inadvertently do not miss the fields and fill in everything correctly, it is worth checking the input data.

This can be done in both PHP on the server side and JS on the client side. I use the second option, because this way a person can immediately find out what he did wrong and correct the mistake without making additional page transitions.

The script code is inserted in the same file where we have the HTML part of the form. For our case, it will look like this:

< script>function checkForm(form) ( var name = form. name. value; var n = name. match(/ ^[ A- Za- zA- Za-z] * [ A- Za- zA- Za-z] + $/ ) ; if (! n) ( alert( "The name was entered incorrectly, please correct the error") ; return false ; ) var phone = form. phone. value; var p = phone. match(/ ^[ 0 - 9 + ] [ 0 - 9 - ] * [ 0 - 9 - ] + $/ ) ; if (! p) ( alert( "Phone entered incorrectly") ; return false ; ) var mail = form. mail. value; var m = mail . match(/ ^[ A- Za- z0- 9 ] [ A- Za- z0- 9 \. _- ] * [ A- Za- z0- 9 _] *@ ([ A- Za- z0- 9 ] + ([ A- Za- z0- 9 - ] * [ A- Za- z0- 9 ] + ) * \. ) + [ A- Za- z] + $/ ) ; if (! m) ( alert( "Email entered is incorrect, please correct the error") ; return false ; ) return true ; )

Well, now the usual analysis:

For that, so that when you click on the submit button of the form, we have it validated we hang the launch of our script on the form tag:

< form method= "post" action= "mail.php" onSubmit= "return checkForm(this)" >

Now, point by point, we take the composition of the check:


As you can see, such a mini check is written for each of our fields. I highlighted the check for one field in the screenshot with a red square, for other fields it has a similar structure, and if you need to add a field or remove it, you can now easily do it.

Share with friends or save for yourself:

Loading...