# Reading Request Data
Usually data sent in a POST request is structured key/value pairs with a MIME type of application/x-www-form-urlencoded . However many applications such as web services require raw data, often in XML or JSON format, to be sent instead. This data can be read using one of two methods.
php://input is a stream that provides access to the raw request body.
$HTTP_RAW_POST_DATA is a global variable that contains the raw POST data. It is only available if the always_populate_raw_post_data directive in php.ini is enabled.
This variable has been deprecated since PHP version 5.6, and was removed in PHP 7.0.
Note that neither of these methods are available when the content type is set to multipart/form-data , which is used for file uploads.
# Reading POST data
Data from a POST request is stored in the superglobal
(opens new window) $_POST in the form of an associative array.
Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.
# Reading GET data
Data from a GET request is stored in the superglobal
(opens new window) $_GET in the form of an associative array.
Note that accessing a non-existent array item generates a notice, so existence should always be checked with the isset() or empty() functions, or the null coalesce operator.
Example: (for URL /topics.php?author=alice&topic=php )
# Handling file upload errors
The $_FILES["FILE_NAME"][‘error’] (where "FILE_NAME" is the value of the name attribute of the file input, present in your form) might contain one of the following values:
- UPLOAD_ERR_OK — There is no error, the file uploaded with success.
- UPLOAD_ERR_INI_SIZE — The uploaded file exceeds the upload_max_filesize directive in php.ini .
- UPLOAD_ERR_PARTIAL — The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
- UPLOAD_ERR_NO_FILE — No file was uploaded.
- UPLOAD_ERR_NO_TMP_DIR — Missing a temporary folder. (From PHP 5.0.3).
- UPLOAD_ERR_CANT_WRITE — Failed to write file to disk. (From PHP 5.1.0).
- UPLOAD_ERR_EXTENSION — A PHP extension stopped the file upload. (From PHP 5.2.0).
An basic way to check for the errors, is as follows:
# Uploading files with HTTP PUT
(opens new window) for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:
Into your PHP code you would then do something like this:
(opens new window) you can read interesting SO question/answers about receiving file via HTTP PUT.
# Passing arrays by POST
Usually, an HTML form element submitted to PHP results in a single value. For example:
This results in the following output:
However, there may be cases where you want to pass an array of values. This can be done by adding a PHP-like suffix to the name of the HTML elements:
This results in the following output:
You can also specify the array indices, as either numbers or strings:
Which returns this output:
This technique can be used to avoid post-processing loops over the $_POST array, making your code leaner and more concise.
# Remarks
# Choosing between GET and POST
GET requests, are best for providing data that’s needed to render the page and may be used multiple times (search queries, data filters. ). They are a part of the URL, meaning that they can be bookmarked and are often reused.
POST requests on the other hand, are meant for submitting data to the server just once (contact forms, login forms. ). Unlike GET, which only accepts ASCII, POST requests also allow binary data, including file uploads
You can find a more detailed explanation of their differences here
# Request Data Vulnerabilities
Retrieving data from the $_GET and $_POST superglobals without any validation is considered bad practice, and opens up methods for users to potentially access or compromise data through code
(opens new window) . Invalid data should be checked for and rejected as to prevent such attacks.
Request data should be escaped depending on how it is being used in code, as noted here
(opens new window) . A few different escape functions for common data use cases can be found in this answer
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:
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
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:
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
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.
Работа с формами
Одно из главнейших достоинств PHP — то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел Переменные из внешних источников. Вот пример формы HTML:
Пример #1 Простейшая форма HTML
В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо специальных тегов. Когда пользователь заполнит форму и нажмёт кнопку отправки, будет вызвана страница action.php . В этом файле может быть что-то вроде:
Пример #2 Выводим данные формы
Пример вывода данной программы:
Если не принимать во внимание куски кода с 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.
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 minimise the risk of your users getting code (ADs) injected into your traffic that wasn’t put there by you.
Post php что это
Одним из основных способов передачи данных веб-сайту является обработка форм. Формы представляют специальные элементы разметки HTML, которые содержат в себе различные элементы ввода — текстовые поля, кнопки и т.д. И с помощью данных форм мы можем ввести некоторые данные и отправить их на сервер. А сервер уже обрабатывает эти данные.
Создание форм состоит из следующих аспектов:
Создание элемента <form><form> в разметке HTML
Установка метода передачи данных. Чаще всего используются методы GET или POST
POST-запросы
Итак, создадим новую форму. Для этого определим новый файл form.php , в которое поместим следующее содержимое:
Атрибут action=»user.php» элемента form указывает, что данные формы будет обрабатывать скрипт user.php , который будет находиться с файлом form.php в одной папке. А атрибут method=»POST» указывает, что в качестве метода передачи данных будет применяться метод POST.
Теперь определим файл user.php , который будет иметь следующее содержание:
Для обработки запросов типа POST в PHP используется встроенная глобальная переменная $_POST . Она представляет ассоциативный массив данных, переданных с помощью метода POST. Используя ключи, мы можем получить отправленные значения. Ключами в этом массиве являются значения атрибутов name у полей ввода формы.
Например, так как атрибут name поля ввода возраста имеет значение age ( <input type=»number» name=»age» /> ), то в массиве $_POST значение этого поля будет представлять ключ «age»: $_POST[«age»]
И поскольку возможны ситуации, когда поле ввода будет не установлено, то в этом случае желательно перед обработкой данных проверять их наличие с помощью функции isset() . И если переменная установлена, то функция isset() возвратит значение true .
Теперь мы можем обратиться к скрипту form.php и ввести в форму какие-нибудь данные:
И по нажатию кнопки введенные данные методом POST будут отправлены скрипту user.php :
Необязательно отправлять данные формы другому скрипту, можно данные формы обработать в том же файле формы. Для этого изменим файл form.php следующим образом:
Поскольку в данном случае мы отправляем данные этому же скрипту — то есть по тому же адресу, то у элемента форма можно не устанавливать атрибут action .
Стоит отметить, что в принципе мы можем отправлять формы и запросом GET, в этом случае для получения тех же значений формы применяется массив $_GET , который был рассмотрен в прошлой теме: