Contacts

Outputting form submitted data to php. Creation of HTML forms. II. Entering data through a loop

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

HTML form for submitting data

The form on the page is formed by tags

...
, inside which the tags of the input fields are placed text information, tags for special components (for example, a combo box), tags for a select box, 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, you need to specify the "form" attribute to determine which form of submission it should interact with.

So, simplest form sending may contain the following code:


Value A:
Value B:

Form elements and their parameters:

action = "myform.php"- the "action" attribute defines which php file will process the sent data. In this example, the data will be sent to the file "myform.php" located in the same directory as the page with the form. If you do not explicitly specify this attribute, the form data will be sent to the page address of the form itself.

method = "post"- the method parameter defines the method of data transmission POST or GET. More details on this in the article "Differences between POST and GET methods". If you do not specify the attribute explicitly, the GET method will be used by default.

Text "Meaning A:" and "Value B:" added only for the purpose of design and clarity 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, changes and appearance element, and its purpose. The value of the "text" attribute indicates that the browser will render the element 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 the passed value can then be accessed in the php handler. The name can be chosen arbitrarily, however, it is more convenient when this value has some understandable meaning.

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

value = "(! LANG: Send" !}- in this case (for type = "submit") only defines 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 this way is placed in the $ _POST, $ _GET and $ _REQUEST superglobal arrays. $ _POST or $ _GET will contain data depending on which method was used to send. $ _REQUEST contains the 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 variables to the values ​​of the elements of such an array by specifying the field name as an index:

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

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

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

Checking the completion 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 has been filled in";
$ 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 deliberately enters zero for calculations, then the empty function will show that there is no value. Therefore, it is better to use the isset function for such situations. It will explicitly check if the value is given or not.

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

or how to send a message by e-mail using HTML forms

You have your own website and want to receive letters or messages from your users, questions, advice or just wishes about e-mail then this tutorial is for you!

How to send a message by e-mail

We need the following files:

  1. form.html - a page with a form.
  2. form_processing.php - script file, processing HTML form.

Consider the form.html code:

Processing HTML form with PHP



Your name:


Email:


Topic:


Message:







HTML form contains fields for entering a name, mailing address the user, the subject of the message, the text of the message and the "Send" button, when you click on which, the information is sent for processing to PHP script in the form_processing.php file.

The Hypertext Transport Method has two meanings: get (the default) and post. More commonly used post method, since it allows you to transfer large amounts of data. All values ​​passed to the processing script via the post method are stored in associative array$ _POST (this array is originally built into the php interpreter), which consists of $ _POST variables, where name is the actual name of the input field - the value of the name = "" attribute:

Let's create a handler file form_processing.php:

/ * We check the input data and protect them from hostile
scripts * /
$ your_name = htmlspecialchars ($ _POST ["your_name"]);
$ email = htmlspecialchars ($ _POST ["email"]);
$ tema = htmlspecialchars ($ _POST ["tema"]);
$ message = htmlspecialchars ($ _POST ["messages"]);
/ * Set the recipient's e-mail * /
$ myemail = " [email protected]" ;
/ * Check if required input fields are filled using check_input
function * /
$ your_name = check_input ($ _POST ["your_name"], "Enter your name!");
$ tema = check_input ($ _POST ["tema"], "Please enter a subject for your message!");
$ email = check_input ($ _POST ["email"], "Enter your e-mail!");
$ message = check_input ($ _POST ["message"], "You forgot to write a message!");
/ * Check if the e-mail is written correctly * /
if (! preg_match ( "/( [\w\->+\@ [\w\->+\. [\w\-†+)/", $ email))
{
show_error ( "
Email address does not exist "
);
}
/ * Create a new variable by assigning a value to it * /
$ message_to_myemail = "Hello!
Your contact form has been sent a message!
Sender name: $ your_name
E-mail: $ email
Message text: $ message
End"
;
/ * Send a message using the mail () function * /
$ from = "From: $ yourname<$email>\ r \ n Reply-To: $ email \ r \ n ";
mail ($ myemail, $ tema, $ message_to_myemail, $ from);
?>

Your message has been successfully sent!


Home >>>


/ * If errors were made when filling out the form, it will work
the following code: * /
function check_input ($ data, $ problem = "")
{
$ data = trim ($ data);
$ data = stripslashes ($ data);
$ data = htmlspecialchars ($ data);
if ($ problem && strlen ($ data) == 0)
{
show_error ($ problem);
}
return $ data;
}
function show_error ($ myError)
{
?>


Please correct the following error:







exit ();
}
?>

Code section:

- will display the specified text if the fields HTML forms were filled in correctly. index.php - home page your site.

Code section:

- will indicate the nature of the error.

Variable value:

$ from = "From: $ yourname<$email>\ r \ n Reply-To: $ email \ r \ n ";
?>

- will automatically display the user's e-mail in the correct line when you write a response.

PHP Form - Working with Forms in PHP is the eighth lesson of the PHP tutorial. In this tutorial we will talk about PHP form processing.

Working with forms

PHP allows you to process data that the user has entered into form fields. After the submit button is activated, the data is sent to the handler page specified in the action field of the element

... On the page - the handler is located PHP script, which performs certain operations on the received data, for example, generates and sends a letter according to the details specified by the user.

Passing data to the handler.

The data from the form is sent to the server as a sequence of name / value pairs. This means that the name of each form element (appearing in the NAME attribute of the tag) is associated with the value of that element (entered or selected by the user). The name / value format used for transmission is name = value.

All data passed from the form to the handler program is located in the following superglobal arrays: $ _ GET, $ _POST, and $ _REQUEST.

$ _GET - contains all values ​​passed by the GET method.

$ _POST - Contains all values ​​passed by the POST method.

$ _REQUEST - Contains all values ​​passed by POST and GET methods.

Surname:

Town:

Message:

After pressing the button submit of this form, all data is passed to the handler process.php ... Since this form uses the method POST , then all variables will be located inside the array$ _POST.

Now let's create a handler:

echo "Name: ". $ _POST ["FName"]. "
»;
echo "Last name: ". $ _POST ["LName"]. "
»;
echo "City: ". $ _POST ["City"]. "
»;
echo "
»;
echo "Your message:". $ _POST ["Message"];
?>

Place this file inside the directory with the form page. Now, when using the form, the data will be passed to the handler, which will display a message containing the user data.

$ _Request array

Using a superglobal array$ _Request very convenient, especially when it is not known by what method the data was transferred.

Thanks to foreach loop you can iterate over the values ​​of the $ _Request array.

V this example we display all the values ​​in the $ _Request array. This can be done to check the correctness of user input. That is, the user enters data into the form, clicks submit, but instead of processing the data, a message is displayed on his screen with the data entered by him and the inscription confirm or refuse. This idea has been applied on many sites, and indeed in many programs.

In this tutorial, we learned how to use PHP to process forms. As you can see PHP is a powerful form processing tool, allowing you to perform a wide variety of manipulations with user data, such as storing user data in a database for subsequent authorization, sending a message to the user's mail, and much more.

In the next lesson, we will learn how to validate user input before processing it directly.

Good day to all. Alexey Gulynin is in touch. In the last article, you learned about what serialization is in php. In this article, I would like to talk about how to work with forms in PHP. PHP language is designed for web scripting, and form processing is perhaps the most important in this process. Nowadays, you will not come across sites on which, for example, there would be no registration or a form feedback, or a questionnaire. Forums, online stores, adding a comment, sending a message to social network- all this is the processing of data placed in the form fields. Let's use an example to figure out how process forms in PHP.
We will implement a simple task: you need to create 2 fields (first and last name), transfer this data to the action.php script, as a result, a greeting should come out "Welcome, last name first name"... Who has forgotten how forms are created, and what fields there are, you can see. Let's create a test.html file:

Name: Surname:



Please note that the action.php file (in our case) must be located in the same folder as the test.html file. Here you can specify both relative and absolute paths. Be careful, many errors are associated with incorrectly specifying the path to the form-handler script.

Let's create an action.php file with the following content:

If we now open the test.html file, fill in the form fields and click on the button, we will get to the action.php file, where a message will be displayed. In this case, the browser refers to the action.php script and passes it to it through the "?" all the values ​​of the name attributes located inside the tags separated by &. Note what is substituted for $ _SERVER.

We can solve our problem by parsing the QUERY_STRING string using standard functions on working with strings in PHP, but it is better to use another mechanism - this is using the $ _REQUEST array. PHP places all data received from form fields into the $ _REQUEST array, regardless of how the data was transferred: POST or GET (you can find out through $ _SERVER ["REQUEST_METHOD"]). Let me remind you how these methods differ:

The GET method is public, the POST method is private, i.e. they differ in the way they are passed parameters. Example:

1) If we use the post method: mysite.ru/request.php.
2) If we use the get method: mysite.ru/request.php?myname=ansAlexans&surname=Gulynin ".

Also, in addition to the $ _REQUEST array, PHP creates the $ _GET and $ _POST arrays. Let's now implement our task, based on the knowledge gained:

If we now fill out the form and click on the button, we will see that the action.php script greets us by last name and first name. Everything works correctly.

Everything is fine here, but if we change the name of the script, then we will need to make changes to the test.html file. Let's modify the action.php file so that, by accessing it, either a form is displayed when we have not submitted anything, or a greeting when we clicked the button:

"> Name: Surname:


Now we do not depend on the name of the script, because we set it through the environment variable $ _SERVER ["SCRIPT_NAME"]. = $ _ SERVER ["SCRIPT_NAME"]?> Is equivalent to .
In addition to the SCRIPT_NAME environment variable, there are many others.

JavaScript is blocked in your browser. Please enable JavaScript for the site to work!

Working with forms

HTML forms are used to transfer data from the user of the Web page to the server. There are a number of special tools for working with forms in PHP.

Predefined Variables

PHP has a number of predefined variables that do not change when all applications run in a particular environment. They are also called environment variables or environment variables. They reflect the settings of the Apache Web server environment as well as the request information for the given browser. It is possible to get the values ​​of the URL, query string and other elements of the HTTP request.

All predefined variables are contained in the $ GLOBALS associative array. In addition to environment variables, this array also contains global variables defined in the program.

Example 1

Viewing $ GLOBALS Array $ value) echo "\ $ GLOBALS [\" $ key \ "] == $ value
"; ?>

As a result, a list of all global variables, including environment variables, will appear on the screen. The most commonly used ones:

VariableDescriptionContent
$ _SERVER ["HTTP_USER_AGENT"]Client name and versionMozilla / 5.0 (compatible; Googlebot / 2.1; + http: //www.google.com/bot.html)
$ _SERVER ["REMOTE_ADDR"]IP address5.9.142.17
getenv ("HTTP_X_FORWARDED_FOR")Internal IP address of the client
$ _SERVER ["REQUEST_METHOD"]Request method (GET or POST)GET
$ _SERVER ["QUERY_STRING"]On a GET request, encoded data passed along with the URL
$ _SERVER ["REQUEST_URL"]The complete address of the client, including the query string
$ _SERVER ["HTTP_REFERER"]Address of the page from which the request was made
$ _SERVER ["PHP_SELF"]The path to the executable program/index.php
$ _SERVER ["SERVER_NAME"]Domainsite
$ _SERVER ["REQUEST_URI"]Path/php/php_form.php

Handling user input

The PHP input processing program can be separated from the HTML text containing the input forms, or it can be placed on a single page.

Example 2

Input processing example

"method =" post ">

Card number:



There is no data transfer button here, because a single field form is submitted automatically when a key is pressed .

When processing an item with a multivalued selection, you need to add a pair of square brackets to the item name to access all the selected values. To select multiple items, hold down the Ctrl key.

Example 3.1

List



RESULT OF EXAMPLE 3.1:

Example 3.2

Processing the list from the ex1.htm file

    "; foreach ($ Item as $ value) echo"
  • $ value "; echo"
"; ?>

Example 4. Receiving values ​​from checkboxes

$ v) (if ($ v) echo "You know the $ k programming language!
"; else echo" You don't know the $ k programming language.
"; } } ?>
"method =" post "> What programming languages ​​do you know?
PHP
Perl

RESULT OF EXAMPLE 4:

Example 5

"; ?>
"method =" post ">

It is possible to process forms without worrying about the actual field names.

To do this, you can use (depending on the transfer method) the associative array $ HTTP_GET_VARS or $ HTTP_POST_VARS. These arrays contain name / value pairs for each element of the submitted form. If you don't care, you can use the $ _REQUEST associative array.

Example 6

Handling arbitrary input regardless of the transfer method $ value) echo "$ key == $ value
"; ?>

Example 7. Handling a click on a button using the "@" operator.

">

Using the header () function, by sending the "Location" header to the browser, you can redirect the user to a new page.

For instance:

File transfer to the server. Upload file. UpLoad

PHP allows you to transfer files to the server. The HTML form for submitting the file must contain the argument enctype = "multipart / form-data".

In addition, there must be a hidden field named max_file_size in front of the file copy field in the form. This hidden field should contain the maximum size of the transferred file (usually no more than 2 MB).

The file transfer field itself is a regular INPUT element with the type = "file" argument.

For instance:

"method =" post ">

After the file is uploaded to the server, it is uniquely named and stored in the temporary directory. The full path to the file is written into a global variable, the name of which is the same as the name of the field for transferring this file. In addition, PHP stores some additional information about the transferred file in other global variables:

Example 8

Processing the transferred file "; echo" name: ". $ _ FILES [" userfile "] [" name "]."
"; echo" size: ". $ _ FILES [" userfile "] [" size "]."
"; echo" type: ". $ _ FILES [" userfile "] [" type "]."
"; } ?>
"method =" post ">



Examples of uploading files to the server

If you have problems with the server transcoding the uploaded file, the symbol with the code 0x00 replaced by a space (character with code 0x20), add to the file httpd.conf from the Apache directory (/ usr / local / apache) the following lines.

CharsetRecodeMultipartForms Off



Did you like the article? Share it