Imaginary submit php. Html forms: php form - send a request to the same page. How to Avoid Trouble with PHP _SELF

I spent a long time thinking about what title to give this article and couldn’t come up with anything better. This is the only title that at least somehow reflects the essence of what is stated. To be honest, I don’t know what it’s called correctly, so I named the article the same way I tried to find at least some information in a search engine on this topic.

On one of the sites, I needed to use two submit buttons in one form, which would send the filled data to different PHP “handlers”, depending on when the button was pressed. Google didn’t answer me anything reasonable, apparently I just didn’t ask it the right way, so I had to come up with it myself.

So I laid it out for your consideration.

The essence of the problem

After implementing it myself, I still found several solutions that were based on the use of regular buttons to which JS was screwed.

I implemented my plan in almost the same way, but used the standard submit type. Everything seems to be working and in my opinion my solution is more logically correct.

This solution will work equally well both on free hosting and if you choose professional hosting. This method is implemented entirely on the client side and should not slow down the server.

To make it easier to understand what I want and how it works, here is a really working example, in the form of a form that has 2 submits that send data to different pages.

One of the great things about PHP is the way it works with HTML forms. The main thing here is that each form element automatically becomes available to your PHP programs. For detailed information about using forms in PHP, read the section. Here's an example HTML form:

Example #1 Simplest HTML Form

Your name:

Your age:

There is nothing special about this form. This is a regular 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 have something like:

Example #2 Displaying form data

Hello, .
You are old.

Example output of this program:

Hello, Sergey. You are 30 years old.

If you don't take into account the pieces of code with htmlspecialchars() and (int), the operating principle of this code should be simple and understandable. 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 should be a number, we can simply convert to an integer, which will automatically get rid of the unwanted characters. PHP can also do this automatically using the filter extension. The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. Previously we used the $_SERVER superglobal variable, but here we also use the $_POST superglobal variable, which contains all the POST data. notice, that sending method(method) of our form is POST. If we used the method GET, then our form information would be in the superglobal variable $_GET . Alternatively, you can use the $_REQUEST variable if the data source does not matter. This variable contains a mixture 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. If you click "Reload" or "Refresh" on a page that you reached through a POST, it"s almost always an error -- you shouldn"t be posting the same comment twice -- 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 the 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.

The POST and GET methods are mainly used to transfer parameters from forces. The main difference between the POST and GET methods is the way information is transferred. In the GET method, parameters are passed through the address bar (URL), i.e. in the HTTP request header, while in the POST method the parameters are transmitted through the body of the HTTP request and are not reflected in the address bar.

1. Buttons - Tag

The tag creates buttons on a web page and its action resembles the result obtained using the tag (with the type="button | reset | submit" parameter). Unlike this tag, it offers advanced options for creating buttons. For example, on such a button you can place any HTML elements, including images. Using styles, you can define the appearance of a button by changing the font, background color, size and other parameters.

In theory, the tag should be located inside the form set by the element. However, browsers do not display an error message and work correctly with the tag if it is encountered on its own. However, if you need to send the result of clicking on the button to the server, it must be placed in a container. The closing tag is required.

Options:

disabled - blocks access and modification of the element.

type - button type

value - The value of the button that will be sent to the server or read using sprits.

Button with text

Parameter DISABLED Blocks access and modification of the button. In this case, it is displayed gray and cannot be activated by the user. Additionally, such a button cannot gain focus by pressing the Tab key, using the mouse, or otherwise. However, this button state can be changed through scripts.

Active button Inactive button

Parameter TYPE Specifies the type of button, which sets its behavior on the form. The different types of buttons do not differ in appearance in any way, but each button has its own functions. Default value: button.

Arguments:

button - Regular button.

reset - A button for clearing the entered form data and returning the values ​​to their original state.

Submit - Button for sending form data to the server.

Clear form Submit form

Parameter VALUE Specifies the value of the button that will be sent to the server. A “name=value” pair is sent to the server, where the name is specified by the name parameter of the tag, and the value is specified by the value parameter. The meaning can either coincide with the text on the button or be independent. The value parameter is also used to access data through scripts.

Submit form

1.1. Button (input type=button) 1.2. Button with an image (input type=image) Button with a picture

Buttons with images are similar in action to the Submit button, but they represent a picture. To do this, set type=image and src="image.gif" .

When the user clicks anywhere on the image, the corresponding form will be submitted to the server with two additional variables - sub_x and sub_y . They contain the coordinates of the user clicking on the image. Experienced programmers may notice that the variable names sent by the browser actually contain a dot rather than an underscore, but PHP automatically converts the dot to an underscore.

1.3. Form submit button (input type=submit)

Serves to submit the form to the script. When creating a button to submit a form, you must specify 2 attributes: type="submit" and value="Button text" . Атрибут name необходим, если кнопка не одна, а несколько и все они созданы для разных операций, например кнопки "Сохранить", "Удалить", "Редактировать" и т.д. После нажатия на кнопку сценарию передается строка имя=текст кнопки.!}

No PHP script required.

1.4. An array of buttons (submit) for selecting action option 2. Form reset button (Reset)

When you click the reset button, all form elements will be set to the state that was specified in the default attributes, and the form will not be submitted.

No PHP script required.

3. Checkbox

Checkboxes present the user with a number of options, and allow arbitrary selection (none, one, or more of them).

White
Green
Blue
Red
Black

// first set of buttons
// second set of buttons
// third set of buttons

5. Text field (text)

When creating a regular text field of size size and the maximum allowed length of maxlength characters, the type attribute takes on the value text . If the value parameter is specified, the field will display the value specified in the variable. When creating a field, do not forget to specify the field name, because... this attribute is required.

6. Password field

Exactly the same as a text field, except that the characters typed by the user will not be displayed on the screen.

7. Hidden text field (hidden)

Allows you to pass some service information to the script without displaying it on the page.

8. Dropdown list (select)

A tag is a drop-down or expanded list, and one or more rows can be selected at the same time. But the value will be passed to the last selected button.

The list starts with paired tags. Tags allow you to define the contents of the list, and the value parameter defines the value of the string. If the selected parameter is specified in the tag, then the row will be initially selected. The size parameter specifies how many lines the list will occupy. If size is 1 , then the list will be a dropdown. If the multiple attribute is specified, then multiple elements from the list can be selected. But this scheme is practically not used, and with size = 1 it makes no sense.

White Green Blue Red Black

If you need to create a drop-down with a predictable sequence. For example, a list with years from 2000 to 2050. Then the following technique is used.

9. Multiline text input field (textarea)

A multi-line text input field allows you to send not just one line, but several at once. If necessary, you can specify the readonly attribute, which prohibits editing, deleting and changing the text, i.e. the text will be read-only. If it is necessary for the text to be initially displayed in a multi-line input field, then it must be placed between the tags.

There is a wrap parameter - setting line wrapping. Possible values:

off - disables line wrapping;

virtuals - shows line breaks, but sends the text as it was entered;

physical - line breaks are left in their original form.

By default, the tag creates a blank field that is 20 characters wide and consists of 2 lines.


In order for a multi-line text field to comply with html formatting (line wrapping using the tag
or
), then use the nl2br() function:

Originally inserted line 1 Originally inserted line 2 Originally inserted line 3

10. Button for uploading files (browse)

Serves to implement uploading files to the server. When creating a text field, you also need to specify the field's type as "file" .

Upload file:

WAYS TO COMMUNICATE THE BROWSER WITH THE SERVER

There are few methods provided by the HTTP protocol. This is important information. There are no other ways. In practice, two are used: GET is when data is transferred in the address bar, for example, when the user clicks a link. POST - when he clicks a button on the form.

GET method

To transfer data using the GET method, you do not need to create a form on an HTML page (nobody forbids you to use forms for requests using the GET method - but this is stupidity) - just a link to the document with the addition of a query string that can look like a variable=value pairs are combined using an ampersand & and the string is appended to the page URL using a question mark “? "

But you don’t have to use key=value pairs if you need to pass just one variable; to do this, you need to write the VALUE (not the name) of the variable after the question mark.

The advantage of passing parameters in this way is that clients that cannot use the POST method (for example, search engines) can still simply pass the parameters to the script by following the link and receive the content.

The downside is that simply by changing the parameters in the address bar the user can turn the script around in an unpredictable way, this creates a huge security hole when combined with undefined variables and register_globals on or someone could find out the value of an important variable (like the session ID) just by looking on the monitor screen.

To access public pages by passing parameters (increased functionality)

Transfer of information that does not affect the security level

To access protected pages with parameters passed

To transmit information affecting the security level

To transmit information that cannot be modified by the user (some transmit the text of SQL queries.

POST method

You can submit data using the POST method only using a form on an HTML page. The main difference between POST and GET is that the data is transmitted not in the request header but in the body, therefore the user does not see it. It can only be modified by changing the form itself.

Advantage :

Greater security and functionality for requests using POST forms.

Flaw :

Less availability.

What should you use it for:

To transmit a large amount of information (text, files..);

To transmit any important information;

To restrict access (for example, use only the form for navigation - an option not available to all robot programs or content grabbers).

What should not be used for:

No restrictions.

Uploading files using the POST method

PHP is capable of accepting a file downloaded using any browser. This makes it possible to upload both text and binary files. Combined with PHP authentication and file system functions, you have full control over who is allowed to upload files and what to do with the file once it has been uploaded.

The file upload page can be implemented using a special form that looks something like this:

//Form for uploading files Send this file:

In the example above, "_URL_" needs to be replaced with a link to the PHP script. The hidden field MAX_FILE_SIZE (the value must be specified in bytes) must precede the file selection field, and its value is the maximum allowed file size to be accepted. You should also make sure that you specify enctype="multipart/form-data" in the form attributes, otherwise the files will not be uploaded to the server.

Attention

The MAX_FILE_SIZE option is a browser recommendation, even if PHP would also check for this condition. Bypassing this limitation on the browser side is fairly easy, so you should not rely on this feature to block all larger files. However, there is no way to bypass PHP's maximum size limitation. You should add a variable of the form MAX_FILE_SIZE anyway, as it prevents users from waiting anxiously while transferring huge files, only to find out that the file is too large and the transfer actually failed.

How to define a request method?

Directly:

Getenv("REQUEST_METHOD");

will return GET or POST.

Which method should be used?

If the form is used to request some information, for example during a search, then it should be sent using the GET method. To be able to update the page, you could bookmark it and or send the link to a friend.

If, as a result of submitting a form, data is recorded or changed on the server, then it should be sent using the POST method, and after processing the form, it is imperative to redirect the browser using the GET method. Also, POST may be needed if a large amount of data needs to be transferred to the server (for GET it is very limited), and also if the transferred data should not be displayed in the address bar (when entering a login and password, for example).

In any case, after processing the POST, you should always redirect the browser to some page, even the same one, but without the form data, so that when the page is refreshed, they are not recorded again.

How to transfer data to another file directly from the body of a PHP program using GET and POST methods? An example to demonstrate sending data using the POST and GET methods simultaneously and receiving a response from the server.

This article discusses the use of the PHP _SELF variable in detail.

What is the PHP _SELF variable?

The PHP _SELF variable returns the name and path of the current file (relative to the document root). You can use this variable in the form's action attribute. There are also some nuances that you should know. Of course, we cannot ignore these nuances.

Let's look at a few examples.

Echo $_SERVER["PHP_SELF"];

1) Let's assume that your php file is located at the following address:

Http://www.yourserver.com/form-action.php

In this case, the PHP _SELF variable will contain:

"/form-action.php"

2) Let's assume your php file is located at this address:

Http://www.yourserver.com/dir1/form-action.php

PHP_SELF will be:

"/dir1/form-action.php"

PHP _SELF in the form's action attribute. Why was she needed there?

Typically the PHP _SELF variable is used in the action attribute of the form tag. The action attribute specifies the address to which the contents of the form will be sent after confirmation (the user clicks on the button with type="submit"). As a rule, this is the same page from which the form left.

However, if you rename the file referenced by the form, you will need to rename the file name in the action attribute, otherwise the form will not work.

The PHP _SELF variable will save you from unnecessary corrections, since the page address will be generated automatically based on the file name.

Let's say you have a form file called form-action.php and you want the form to be submitted to the same file after confirmation. Usually they write like this:

But you can use the PHP _SELF variable instead of form-action.php. In this case the code will look like: