Как сделать 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 , который был рассмотрен в прошлой теме:
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:
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.
Как отправить HTTP запрос методом POST на URL через PHP?

Действительно, за время, которое потратили на создание вопроса, Вы могли без проблем найти интересующую Вас информацию в любом поисковике.
Но раз вопрос уже задан, то должен быть и ответ(ы).
Собственно, @OnYourLips дал ссылку на хороший фреймворк, но если нет смысла тащить в проект/скрипт целый фреймворк ради одного запроса, к примеру, то логичнее воспользоваться упомянутым CURL. В Вашем случае сценарий использования CURL будет выглядеть примерно следующим образом:
# 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