Php script in form action

Master PHP Form Action: Guide on GET and POST Methods

If you were following our lessons, you have by now learned how to create PHP forms, how to make certain input fields required, and how to validate the data your users enter. Now it’s time to learn to make sure you get the information users submitted.

A PHP form action attribute specifies the location to transfer the submitted users’ information. You can set the attribute to deliver information to a website or a file.

PHP get and PHP post are superglobal methods, meaning you can use them anywhere in your script. They both send the data users provide to the server. In this tutorial, we will explain in what cases it’s better to choose one or the other and how to use them correctly.

Contents

PHP Form Action: Main Tips

  • PHP form action attribute is used to specify where the data is sent to be processed.
  • Superglobals $_POST and $_GET are used to gather data from PHP forms.
  • GET method is used for non-sensitive data and allows bookmarking pages.
  • POST method is used for sensitive data as it is considered more secure.

A Simple HTML Form

In the code snippet below you can see a simple HTML form containing two input fields with a submit button:

  
"pet.php" method="post"> Pet breed: "text" name="breed">
Color: "text" name="color">
"submit">

After the form is filled in and the submit button is clicked, all data is sent for processing to pet.php, defined in the PHP form action attribute. The method used to send the information is PHP POST.

echo variable is used to display the submitted data. Let’s see the code in the file:

  Your pet breed is:  echo $_POST["breed"]; ?> 
Color is: echo $_POST["color"]; ?>

Now let’s try to achieve the same result using PHP GET method:

  
"pet_get.php" method="get"> Breed: "text" name="breed">
Color: "text" name="color">
"submit">

The file specified in PHP form action attribute (pet_get.php) will now look like this:

  Your pet breed is:  echo $_GET["breed"]; ?> 
Color: echo $_GET["color"]; ?>

One crucial thing that you must always keep in mind is protection. We need to validate the form data to defend the script against any malicious code.

Note: When working with PHP forms, never forget security: validation is crucial. The examples above only describe the way to send and retrieve PHP form data!

  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion

GET and POST Methods

Both PHP POST and GET methods create an array that holds key/value pairs. The key is a form value and the value is the data inputted by the user. GET and POST are treated as superglobals which means they are accessible anywhere.

$_GET is used to pass an array to the script with URL parameters.

$_POST is used to pass an array to the script with the HTTP POST method.

Using PHP GET

Using GET will not hide the information being sent from a form: everything is visible in the URL. Also, this method has limits to the amount of data that could be sent (the threshold is about 2000 characters).

However, as the information is shown in the URL, you can bookmark the pages, and that is pretty useful on some occasions.

In conclusion, this method should be used for processing not sensitive information.

Note: It is very important to emphasise that you should never use the GET method for sending passwords and any sensitive data!

Using PHP POST

Unlike the GET method, the POST method hides data being sent by embedding in the HTTP request body. It also has no limits and supports more advanced functionality like support for multi-part binary input when using an FTP.

Therefore, it shouldn’t come as a surprise most coders prefer the POST method for processing data gathered using PHP forms. The only disadvantage it has is the inability to bookmark particular pages.

PHP Form Action: Summary

  • $_POST and $_GET are superglobal variables meant to collect data from forms. Its destination is defined in PHP form action attribute.
  • POST method is generally deemed more secure, so it’s better to choose it for sensitive data.
  • GET method can’t provide such safety, but allows you to bookmark certain pages.

Источник

Using PHP_SELF in the action field of a form

In this article shows the usage of PHP_SELF variable and how to avoid PHP_SELF exploits.

What is PHP_SELF variable?

PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file (from the root folder). You can use this variable in the action field of the FORM. There are also certain exploits that you need to be aware of. We shall discuss all these points in this article. We will now see some examples. echo $_SERVER[‘PHP_SELF’];

a) Suppose your php file is located at the address: http://www.yourserver.com/form-action.php

In this case, PHP_SELF will contain: «/form-action.php»

b) Suppose your php file is located at the address: http://www.yourserver.com/dir1/form-action.php

For this URL, PHP_SELF will be : «/dir1/form-action.php»

Using the PHP_SELF variable in the action field of the form

A common use of PHP_SELF variable is in the action field of the tag. The action field of the FORM instructs where to submit the form data when the user presses the “submit” button. It is common to have the same PHP page as the handler for the form as well.

However, if you provide the name of the file in the action field, in case you happened to rename the file, you need to update the action field as well; or your forms will stop working.

Using PHP_SELF variable you can write more generic code which can be used on any page and you do not need to edit the action field.

Consider, you have a file called form-action.php and want to load the same page after the form is submitted. The usual form code will be:

 form method="post" action="form-action.php" > 

We can use the PHP_SELF variable instead of “form-action.php”. The code becomes:

form name="form1" method="post" action=" $_SERVER['PHP_SELF']; ?>" > 

The complete code of “form-action.php”

Here is the combined code, that contains both the form and the PHP script.

php if(isset($_POST[‘submit’])) $name = $_POST[‘name’]; echo «User Has submitted the form and entered this name : $name «; echo «
You can use the following form again to enter a new name.»
;
> ?> «>

This PHP code is above the HTML part and will be executed first. The first line of code is checking if the form is submitted or not. The name of the submit button is “submit”. When the submit button is pressed the $_POST[‘submit’] will be set and the IF condition will become true. In this case, we are showing the name entered by the user.

If the form is not submitted the IF condition will be FALSE as there will be no values in $_POST[‘submit’] and PHP code will not be executed. In this case, only the form will be shown.

What are PHP_SELF exploits and how to avoid them

The PHP_SELF variable is used to get the name and path of the current file but it can be used by the hackers too. If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.

 form name="test" action=" $_SERVER['PHP_SELF']; ?>" method="post"> 

Now, if a user has entered the normal URL in the address bar like http://www.yourdomain.com/form-action.php the above code will be translated as:

form name="test" action="form-action.php" method="post"> 

Now consider that the user has called this script by entering the following URL in the browser’s address bar:

In this case, after PHP processing the code becomes:

 form name="test" method="post" action="form-action.php"/> script>alert('xss')script>foo""> 

You can see that this code has added a script tag and an alert command. When this page is be loaded, user will see an alert box. This is just a simple example how the PHP_SELF variable can be exploited.

Any JavaScript code can be added between the “script” tag. . A hacker can link to a JavaScript file that may be located on another server. That JavaScript file can hold the malicious code that can alter the global variables and can also submit the form to another address to capture the user data, for example.

How to Avoid the PHP_SELF exploits

PHP_SELF exploits can be avoided by using the htmlentities() function. For example, the form code should be like this to avoid the PHP_SELF exploits:

form name="test" action="$_SERVER['PHP_SELF']); ?>" method="post"> 

The htmlentities() function encodes the HTML entities. Now if the user tries to exploit the PHP_SELF variable, the attempt will fail and the result of entering malicious code in URL will result in the following output:

form name="test" method="post" action="form-action.php/"><script>alert('xss')& lt;/script><foo"> 

As you can see, the script part is now ‘sanitized’.

So don’t forget to convert every occurrence of «$_SERVER[‘PHP_SELF’]» into «htmlentities($_SERVER[‘PHP_SELF’])» throughout your script.

NOTE: Some PHP servers are configured to solve this issue and they automatically do this conversion.But, why take risk? make it a habit to use htmlentities() with PHP_SELF.

See Also

Categories

  • Calculation Forms
  • HTML Forms
  • PHP Form Handling
  • Form Action
  • Contact Forms
  • Code Snippets
  • Best Practices
  • HTML5 Forms
  • Form Widgets
  • jQuery Form Handling
  • Email Forms
  • Form Mail
  • Web Forms
  • Checkboxes
  • File Upload
  • Google Forms

Источник

Работа с формами

Одно из главнейших достоинств PHP — то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел Переменные из внешних источников. Вот пример формы HTML:

Пример #1 Простейшая форма HTML

В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо специальных тегов. Когда пользователь заполнит форму и нажмёт кнопку отправки, будет вызвана страница action.php . В этом файле может быть что-то вроде:

Пример #2 Выводим данные формы

Пример вывода данной программы:

Здравствуйте, Сергей. Вам 30 лет.

Если не принимать во внимание куски кода с htmlspecialchars() и (int) , принцип работы данного кода должен быть прост и понятен. htmlspecialchars() обеспечивает правильную кодировку «особых» HTML-символов так, чтобы вредоносный HTML или Javascript не был вставлен на вашу страницу. Поле age, о котором нам известно, что оно должно быть число, мы можем просто преобразовать в int , что автоматически избавит нас от нежелательных символов. PHP также может сделать это автоматически с помощью модуля filter. Переменные $_POST[‘name’] и $_POST[‘age’] автоматически установлены для вас средствами PHP. Ранее мы использовали суперглобальную переменную $_SERVER , здесь же мы точно так же используем суперглобальную переменную $_POST , которая содержит все POST-данные. Заметим, что метод отправки (method) нашей формы — POST. Если бы мы использовали метод GET, то информация нашей формы была бы в суперглобальной переменной $_GET . Кроме этого, можно использовать переменную $_REQUEST , если источник данных не имеет значения. Эта переменная содержит смесь данных GET, POST, COOKIE.

В PHP можно также работать и с XForms, хотя вы найдёте работу с обычными HTML-формами довольно комфортной уже через некоторое время. Несмотря на то, что работа с XForms не для новичков, они могут показаться вам интересными. В разделе возможностей PHP у нас также есть короткое введение в обработку данных из XForms.

User Contributed Notes 3 notes

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.

Also, don’t ever use GET method in a form that capture passwords and other things that are meant to be hidden.

Источник

Читайте также:  Style fonts with css
Оцените статью