Form html data output php. The simplest form for sending data to mail using HTML and PHP

To organize the transfer of data to the server using a form, you will need to implement an HTML form in which site visitors will enter their information and PHP code, the purpose of which is to accept and process the received data on the server.

HTML Submission Form

The form on the page is formed by tags

...
, inside which are placed field tags for entering textual information, tags for special components (for example, a combo box), tags for a selection field and file upload .

* For HTML5, it is also possible to place form field tags not inside form tags, but anywhere on the page. At the same time, for each such field, the "form" attribute must be specified in order to determine which form of submission it should interact with.

So, the simplest form submission might contain the following code:


A value:
B value:

Form elements and their parameters:

action="myform.php"– the "action" attribute determines which php file will process the sent data. In this example, the data will be sent to the "myform.php" file located in the same directory as the form page. If this attribute is not specified explicitly, the form data will be sent to the page address of the form itself.

method="post"– the method parameter defines the POST or GET data transfer method. More about this in the article "Differences between POST and GET methods" . If you don't specify the attribute explicitly, the GET method will be used by default.

Text "Value A:" And "Value B:" added only for the purpose of design and understandability of the form for the user. It is not necessary to add this for data transfer, but in order for the user to understand what to enter, it is worth specifying.

tags are used to form various form controls.

type="text"– the "type" attribute defines the type of the field. Depending on which type is specified, the appearance element and its purpose. The value of the "text" attribute specifies that the element will be displayed in the browser as a single-line text field where the user can enter their string.

name="data1"– the "name" attribute indicates the name, or rather the index of the data in the array received by the server. This is a required parameter, by which in the php handler it will be possible to then access the passed value. The name can be chosen arbitrarily, however, it is more convenient when this value has some clear meaning.

type="submit"- tag with this value of the "type" parameter will be displayed on the page as a button. In fact, you can do without a button on the form. If, for example, there are text fields in the form, then sending can be done by simply pressing "Enter" on the keyboard. But having a button makes the form clearer.

value="Submit" !}– in this case (for type="submit") it defines only the caption on the button. For type="text", for example, this will be the text that will be displayed in the text field.

As a result, on the page this code will look something like this:

By clicking on the button, the data will be sent to the specified page, and if it exists and works correctly, the data will be processed.

Processing HTML form submitted data in PHP

The data sent in the described way is placed in the $_POST, $_GET and $_REQUEST superglobal arrays. $_POST or $_GET will contain data depending on which method was sent. $_REQUEST contains submitted data by any of the specified methods.

$_POST, $_GET and $_REQUEST are associative arrays whose index fields match the "name" attributes of the tags . Accordingly, to work with data in the myform.php file, you can assign the values ​​of the elements of such an array to variables by specifying the field name as an index:

// for GET method
$a = $_GET[ "data1" ];
$b = $_GET[ "data2"];

// for the POST method
$a = $_POST[ "data1" ];
$b = $_POST[ "data2"];

// with any method
$a = $_REQUEST[ "data1" ];
$b = $_REQUEST[ "data2"];

Checking the filling of form fields

Sometimes, when receiving data, you need to check if the user has submitted an empty form. You can use the empty function for this.

if (empty ($_REQUEST["data1" ])) (
echo "The field is not filled";
} else(
echo "The field was filled";
$a = $_REQUEST[ "data1" ];
}

Usually this solution is sufficient. If you need to enter text, it will be clear whether it is entered or not. However, if the user enters zero intentionally for the calculation, then the empty function will show that there is no value. Therefore, for such situations, it is better to use the isset function. It will explicitly check if the value is set or not.

if (isset ($_REQUEST["data1" ])) (
echo "The field was filled";
$a = $_REQUEST[ "data1" ];
} else(
echo "The field is not filled";
}

One of the most common tasks in practice is the implementation of a feedback form. Tobish writing its HTML code, styling it in CSS, PHP creation a 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 mailbox does 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.

Interactive sites accept input from users. One common way to receive input is through forms.

In this tutorial, we'll see how to create a form and process input on the server.

When creating a form, two important attributes are involved: action And method.

action Used to enter the URL where the form is submitted. This may be a PHP file that handles input. method Can be "post" or "get", which are different methods of passing data. For now, you don't need to delve into the differences between these methods; the "get" method sends the data via a URL, and the "post" method sends it as a block of data via the standard input service (STDIN). In the last tutorial we went through, we saw how data is retrieved via a URL using $_GET . In this tutorial, we'll look at how the data sent via the "post" method is received.

HTML page with form

The form page doesn't have to be a PHP file (but it can be). It doesn't even have to be on the same site as the file that receives the data.

In our first example, we'll look at a very simple form with a single text field:

Form

Enter your name

The following form will be displayed in the browser:

Now comes the fun part: getting and processing data with PHP.

Requesting form data with PHP

If you need to request data submitted via a form (using the post), you use $_POST :

$_POST["fieldname"];

which will return the value of the form field. Let's try this with an example.

First, let's create a page with a form, as before. Then we will create a PHP page (handler) "handler.php" (note that this is the name of the page that we recorded in the attribute action in our

).

The "handler.php" file will contain:

Form echo "

"; ?>

User input and conditions

In the following example, we will try to use user input to create conditions. First we need a form:

Form

What is your name:

Your favorite color: Red Green Blue

In the browser it will look like this:

We now use these inputs to create a page that automatically changes the background color based on user input. This is done by creating a condition (see Lesson ) that uses the data entered by the user in the form.

$strHeading = "

Hello, " . $_POST["username"] . "

"; switch ($_POST["favoritecolor"]) ( case "r": break; case "g"; break; case "b": break; default: break; ) ?> Form

The background will be white unless the user specifies a preferred color on the form. This is achieved by setting the value default(default), which is applied if none of the conditions are met.

But what happens if the user doesn't provide their name? Then the title will be only "Hi,". Let's create an additional condition to change this option.

$strUsername = $_POST["username"]; if ($strUsername != "") ( $strHeading = "

Hello, " . $_POST["username"] . "

"; ) else ( $strHeading = "

Hello Stranger!

";
} switch ($_POST["favorite color"]) ( case "r": $strBackgroundColor = "rgb(255,0,0)"; break; case "g"; $strBackgroundColor = "rgb(0,255,0)"; break; case "b": $strBackgroundColor = "rgb(0,0,255)"; break; default: $strBackgroundColor = "rgb(255,255,255)"; break; ) ?> Form

In the above example, we use the conditions for checks information from the user. In this case, it is not so important if the user does not specify a name. But as your code gets more and more complex, it's vital that you take into account the option that the user doesn't fill out forms at all.

Example: Contact Form

Based on your knowledge of PHP and forms, you can create a contact information form using the mail function, which has the following syntax:

Mail (where, subject, message);

First, let's create a simple HTML form:

Contact form

Contact form

Subject:

Message:

Then you need a PHP script to send user input:

Functions // Recipient (change to your e-mail address) $strEmail = " [email protected]"; // Get user inputs $strSubject = $_POST["subject"]; $strMessage = $_POST["message"]; mail($strEmail,$strSubject,$strMessage); echo "Mail Sent."; ?>

Note that the example only works if you have access to the mail server. This is not the case by default in XAMPP and most free hosts. So, some hosts may require a form header, which is done with an additional parameter:

Mail ("[email protected]", "Test", "This is a test message", "From: [email protected]");

One of PHP's biggest strengths is how it works with HTML forms. The key here is that each form element is automatically made available to your PHP programs. For more information on using forms in PHP, see the section. Here is an example of an HTML form:

Beispiel #1 The simplest form of HTML

Your name:

Your age:

There is nothing special about this form. This is a normal HTML form without any special tags. When the user fills out the form and clicks the submit button, the action.php page will be called. This file might contain something like:

Beispiel #2 Rendering form data

Hello, .
To youyears.

Sample output from this program:

Hello Sergey. You are 30 years old.

If you do not take into account pieces of code with htmlspecialchars() And (int), the principle of operation of this code should be simple and clear. htmlspecialchars() ensures that "special" HTML characters are properly encoded so that malicious HTML or Javascript is not inserted into your page. The age field, which we know must be a number, we can simply convert to integer, which will automatically get rid of unwanted characters. PHP can also do this automatically with the filter extension. The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal, but here we also use the $_POST superglobal, which contains all the POST data. notice, that sending method(method) of our form is POST. If we were to use the method GET, then our form information would be in the $_GET superglobal. Alternatively, you can use the $_REQUEST variable if the data source is irrelevant. This variable contains a mix of GET, POST, COOKIE data.

15 years ago

According to the HTTP specification, you should use the POST method when you"re using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.

2 years ago

Worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don't want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don't deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren't many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS you minimize the risk of your users getting code (ADs) injected into your traffic that wasn't put there by you.

In one of the previous topics, getting data from a form was already considered. In this topic, I will explain in more detail how the form is sent to the server correctly, as well as how the form is processed in PHP.

Submitting a form

Input field. The most common form elements are various input fields. They are created using the tag many types and tag

select. From tag , and for list items, that is, for tags

Radio button. All radio buttons from the same group must have the same name attribute. This value not only sets the parameter name, but also groups the radio buttons into a group from which only one radio button can be selected. The value attribute is set differently. Let's add radio buttons to the form:

Checkbox. Unlike radio buttons, each checkbox is a separate form element. All checkboxes are independent of each other and each sends its data to the server. The name attribute of all checkboxes must be different, and the value attribute can be either the same or different. However, the checkbox does not have any specific data. It can either be selected or not. Therefore, it makes no sense to set it to a long value. It can be set to a value of one character, for example, 1. On the server, the meaning of this value will be as follows: if there is a value, then the checkbox was selected, and if there is no value, then it is not selected. Let's add checkboxes to the form and create a form submit button:

Processing data from forms

In the proposed example, a form is created that sends data to a script called takeform.php. Therefore, you need to create this script. It will not be just a program, but a page that will be formed depending on the data received from the form. The form is submitted using the POST method. The script takes this data from the $_POST superglobal array. Array elements can be simply used in the script, but if you need to work with them a lot, then writing the name of the element each time is inconvenient. It's easier to write a value to a variable and access it. Let's create a takeform.php file and write the values ​​from the first two form elements into variables:

takeform.php:

To tag