METANIT.COM

Using the POST method in a PHP form

This tutorial will cover how PHP handles form data posted via the POST method.

Introduction to the form

POST data is submitted by a form and “posted” to the web server as form data. POST data is encoded the same way as GET data, but isn’t typically visible to the user in standard browsers.

Most forms use the post method because it “hides” the form data away from the user and doesn’t clutter up the URL in the address bar. Note that GET and POST methods are equally (in)secure.

As easily as a user can monkey with GET data in a URL, the same thing can be done with POST data. You should always assume that the user can submit whatever form and form data that they want to, and process the data accordingly. Don’t trust user input, whether it’s from GET or from POST!

Post data is accessed with the $_POST array in PHP.

php  echo("First name: " . $_POST['firstname'] . "
\\n");
echo("Last name: " . $_POST['lastname'] . "
\\n");
?>
form action="myform5.php" method="post">  p>First name: input type="text" name="firstname" />p>  p>Last name: input type="text" name="firstname" />p>  input type="submit" name="submit" value="Submit" />  form> 

Using “isset”

You can use the “isset” function on any variable to determine if it has been set or not. You can use this function on the $_POST array to determine if the variable was posted or not. This is often applied to the submit button value, but can be applied to any variable.

php  if(isset($_POST['submit'])    echo("First name: " . $_POST['firstname'] . "
\\n");
echo("Last name: " . $_POST['lastname'] . "
\\n");
> ?>
form action="myform5.php" method="post">  p>First name: input type="text" name="firstname" />p>  p>Last name: input type="text" name="firstname" />p>  input type="submit" name="submit" value="Submit" />  form> 

The above code will only display the submitted values if the submit button was clicked.

Can I use both GET and POST in the same page?

GET and POST occupy different spaces in the server’s memory, so both can be accessed on the same page if you want. One use might be to display different messages on a form depending on what’s in the query string.

php  if(isset($_POST['submit'])   if($_GET['lang'] == "english")   echo("First name: " . $_POST['firstname'] . "
\\n");
echo("Last name: " . $_POST['lastname'] . "
\\n");
> else if($_GET['lang'] == "spanish") echo("Nombre: " . $_POST['firstname'] . "
\\n");
echo("Apellido: " . $_POST['lastname'] . "
\\n");
> ?>
form method="post">  p>First name: input type="text" name="firstname" />p>  p>Last name: input type="text" name="firstname" />p>  input type="submit" name="submit" value="Submit" />  form> 

Instead of using GET and POST arrays, you can also use the $_REQUEST array, which will contain the combined contents of the data. If GET and POST variables have the same name, POST will take priority. It’s recommended not to do this unless you really have to, because it can be confusing, and it’s best to be clear about where an input is coming from.

One more thing to notice: the “action” on the form is now missing. Technically, this is not valid HTML. However, by not putting in an action, browsers will assume that the form is submitting to itself. This is important because it will also preserve the querystring when the form is submitted (the ?lang=english part). You can use server variables like $_SERVER[‘PHP_SELF’] and $_SERVER[‘QUERY_STRING’] to build an action value.

Register globals off?

If you are using a version of PHP earlier than 4.2.0, you should strongly consider setting register_globals to “off” in your .htaccess file (if you are using Apache server) for the exact same reasons as were mentioned in the previous tutorial on GET. If you have PHP 4.2.0 or later, don’t worry about it.

More on POST

POST values are unlimited in length, and thus are very well suited for forms, especially forms with a lot of fields.

Источник

Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:

Example #1 A simple HTML form

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:

Example #2 Printing data from our form

A sample output of this script may be:

Hi Joe. You are 22 years old.

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can’t inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an int which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST[‘name’] and $_POST[‘age’] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.

You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.

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.

Источник

Php handle post method

Одним из основных способов передачи данных веб-сайту является обработка форм. Формы представляют специальные элементы разметки HTML, которые содержат в себе различные элементы ввода — текстовые поля, кнопки и т.д. И с помощью данных форм мы можем ввести некоторые данные и отправить их на сервер. А сервер уже обрабатывает эти данные.

Создание форм состоит из следующих аспектов:

  • Создание элемента в разметке HTML
  • Добавление в этот элемент одно или несколько поле ввода
  • Установка метода передачи данных. Чаще всего используются методы GET или POST
  • Установка адреса, на который будут отправляться введенные данные

POST-запросы

Итак, создадим новую форму. Для этого определим новый файл form.php , в которое поместим следующее содержимое:

     

Форма ввода данных

Имя:

Возраст:

Атрибут action=»user.php» элемента form указывает, что данные формы будет обрабатывать скрипт user.php , который будет находиться с файлом form.php в одной папке. А атрибут method=»POST» указывает, что в качестве метода передачи данных будет применяться метод POST.

Теперь определим файл user.php , который будет иметь следующее содержание:

 if(isset($_POST["age"])) < $age = $_POST["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Для обработки запросов типа POST в PHP используется встроенная глобальная переменная $_POST . Она представляет ассоциативный массив данных, переданных с помощью метода POST. Используя ключи, мы можем получить отправленные значения. Ключами в этом массиве являются значения атрибутов name у полей ввода формы.

Например, так как атрибут name поля ввода возраста имеет значение age ( ), то в массиве $_POST значение этого поля будет представлять ключ «age»: $_POST[«age»]

И поскольку возможны ситуации, когда поле ввода будет не установлено, то в этом случае желательно перед обработкой данных проверять их наличие с помощью функции isset() . И если переменная установлена, то функция isset() возвратит значение true .

Теперь мы можем обратиться к скрипту form.php и ввести в форму какие-нибудь данные:

Обработка форм в PHP

И по нажатию кнопки введенные данные методом POST будут отправлены скрипту user.php :

массив <img decoding=

Форма ввода данных

Имя:

Возраст:

Поскольку в данном случае мы отправляем данные этому же скрипту — то есть по тому же адресу, то у элемента форма можно не устанавливать атрибут action .

Отправка формы в PHP

Стоит отметить, что в принципе мы можем отправлять формы и запросом GET, в этом случае для получения тех же значений формы применяется массив $_GET , который был рассмотрен в прошлой теме:

      if(isset($_GET["age"])) < $age = $_GET["age"]; >echo "Имя: $name 
Возраст: $age"; ?>

Форма ввода данных

Имя:

Возраст:

Источник

PHP Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP — A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:

Example

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named «welcome.php». The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The «welcome.php» looks like this:

The output could be something like this:

The same result could also be achieved using the HTTP GET method:

Example

and «welcome_get.php» looks like this:

The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.

Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send and retrieve form data.

However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!

GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, . )). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope — and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

Developers prefer POST for sending form data.

Next, lets see how we can process PHP forms the secure way!

Источник

Читайте также:  Php all to utf 8
Оцените статью