Http post request php

How do I send a POST request using PHP?

Compare Request Timings

What is PHP Curl Library?

Curl and its core library libcurl were created by Daniel Stenberg and allow you to interact with servers through various types of protocols, including HTTP, HTTPS, FTP, and others. Libcurl supports HTTPS certificates, HTTP GET, POST, PUT, PATCH, and other HTTP methods, FTP file uploads (FTP file upload can also be done with PHP FTP extension), HTTP form based uploads, proxies, cookies, and user authentication. To use PHP Curl functions, you need to install libcurl 7.10.5 or newer and compile PHP with Curl support. The behavior of PHP Curl functions is affected by the curl.cainfo setting in the php.ini file.

What is the HTTP POST request method?

The HTTP POST request method is used to send data to the server. For example, to submit login or contact forms, to upload images, or to send JSON, XML, or PDF files to a server.

How to post requests using PHP Curl library?

CURL-less method for sending POST requests using PHP

How to post JSON using PHP?

To send JSON to the server, you must provide a Content-Type: application/json request header and provide the JSON data in the body of the POST message. The Content-Type header allows the server to correctly interpret and process the received data.

How to post XML using PHP?

To post an XML to the server, you must provide a Content-Type: application/xml request header and provide the XML data in the body of the POST message.

How to post HTML Form using PHP?

HTML forms must be submitted with a Content-Type: application/x-www-form-urlencoded request header and form data must be provided as key=value pairs, as shown in the example below.

Источник

How do I send a POST request with PHP?

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method.

16 Answers 16

CURL-less method with PHP5:

See the PHP manual for more information on the method and how to add headers, for example:

Http post request php. Смотреть фото Http post request php. Смотреть картинку Http post request php. Картинка про Http post request php. Фото Http post request php

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That’s why I use http_build_query().

I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.

Installing Guzzle

Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.

Using Guzzle to send a POST request

The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:

I’d like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.

Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:

Improvements

Example of usage

DELETE

Testing

You can also make some cool service tests by using this simple class.

There’s another CURL method if you are going that way.

Источник

http — Как я могу отправить запрос POST с PHP?

На самом деле я хочу прочитать содержимое, которое идет после поискового запроса, когда это будет сделано. Проблема в том, что URL принимает только POST методы, и он не предпринимает никаких действий с GET метод …

Решение

CURL-менее метод с PHP5:

См. Руководство по PHP для получения дополнительной информации о методе и о том, как добавить заголовки, например:

Другие решения

Вы можете использовать cURL:

@Edward упоминает, что http_build_query может быть опущен, так как curl будет правильно кодировать массив, переданный параметру CURLOPT_POSTFIELDS, но имейте в виду, что в этом случае данные будут кодироваться с использованием multipart / form-data.

Я использую эту функцию с API, которые ожидают, что данные будут закодированы с использованием application / x-www-form-urlencoded. Вот почему я использую http_build_query ().

Я рекомендую вам использовать пакет с открытым исходным кодом пропивать это полностью модульное тестирование и использует новейшие практики кодирования.

Установка жрет

Использование Guzzle для отправки запроса POST

Использование Guzzle очень прямолинейно, так как он использует легкий объектно-ориентированный API:

Есть другой метод CURL, если вы идете по этому пути.

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

Если вы не хотите разрабатывать собственную тему или плагин для запуска движка WordPress, вы можете просто сделать следующее в изолированном файле PHP в корне WordPress:

Он не отображает темы и не выводит HTML, просто взломайте API WordPress!

Я хотел бы добавить некоторые мысли об основанном на завитках ответе Фреда Танрикута. Я знаю, что большинство из них уже написаны в ответах выше, но я думаю, что это хорошая идея, чтобы показать ответ, который включает в себя все из них вместе.

Вот класс, который я написал для выполнения запросов HTTP-GET / POST / PUT / DELETE на основе curl, касающихся только тела ответа:

улучшения

Пример использования

ПОЛУЧИТЬ

СООБЩЕНИЕ

ПОЛОЖИЛ

УДАЛЯТЬ

тестирование

Вы также можете сделать несколько крутых тестов сервиса с помощью этого простого класса.

Еще одна альтернатива завиток меньше метод выше это использовать родной поток функции:

Создает и возвращает контекст потока с любыми опциями, предоставленными в опции предустановки.

Источник

$_POST

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_POST — Переменные HTTP POST

Описание

Ассоциативный массив данных, переданных скрипту через HTTP методом POST при использовании application/x-www-form-urlencoded или multipart/form-data в заголовке Content-Type запроса HTTP.

Примеры

Подразумевается, что пользователь отправил через POST name=Иван

Результатом выполнения данного примера будет что-то подобное:

Примечания

Смотрите также

User Contributed Notes 7 notes

One feature of PHP’s processing of POST and GET variables is that it automatically decodes indexed form variable names.

I’ve seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

When they could do this:

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it’s better to define your indexes explicitly.

// Get the JSON contents
$json = file_get_contents ( ‘php://input’ );

$_POST _is_ set for:

In other words, for standard web forms.

$_POST is NOT set for:

A type used for a generic HTTP POST operation.

For a page with multiple forms here is one way of processing the different POST values that you may receive. This code is good for when you have distinct forms on a page. Adding another form only requires an extra entry in the array and switch statements.

// We have not died yet so we must have less than one.
die( «\$_POST did not contain a known post identifier.» );
>

case ‘Modify’ :
echo «Perform actual code for F2_Submit.» ;
break;

Источник

PHP GET/POST request

last modified July 9, 2020

PHP GET/POST request tutorial shows how to generate and process GET and POST requests in PHP. We use plain PHP and Symfony, Slim, and Laravel frameworks.

The is an application protocol for distributed, collaborative, hypermedia information systems. HTTP protocol is the foundation of data communication for the World Wide Web.

HTTP GET

The HTTP GET method requests a representation of the specified resource.

HTTP POST

The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.

PHP GET request

In the following example, we generate a GET request with curl tool and process the request in plain PHP.

We start the server.

We send two GET requests with curl.

PHP POST request

In the following example, we generate a POST request with curl tool and process the request in plain PHP.

We start the server.

We send a POST request with curl.

PHP send GET request with Symfony HttpClient

Symfony provides the HttpClient component which enables us to create HTTP requests in PHP.

We install the symfony/http-client component.

We start the server.

We run the send_get_req.php script.

PHP send POST request with Symfony HttpClient

In the following example, we send a POST request with Symfony HttpClient.

We start the server.

We run the send_post_req.php script.

PHP GET request in Symfony

In the following example, we process a GET request in a Symfony application.

A new application is created.

We install the annot and maker components.

We create a new controller.

Inside the HomeController’s index method, we get the query parameters and create a response.

We start the server.

We generate a GET request with curl.

PHP POST request in Symfony

In the following example, we process a POST request in a Symfony application.

We change the controller to process the POST request.

We start the server.

We generate a POST request with curl.

PHP GET request in Slim

In the following example, we are going to process a GET request in the Slim framework.

We get the parameters and return a response in Slim.

The query parameter is retrieved with getQueryParam ; the second parameter is the default value.

We start the server.

We generate a GET request with curl.

PHP POST request in Slim

In the following example, we are going to process a POST request in the Slim framework.

We get the POST parameters and return a response in Slim.

We start the server.

We generate a POST request with curl.

PHP GET request in Laravel

In the following example, we process a GET request in Laravel.

We create a new Laravel application.

We get the GET parameters and create a response.

We start the server.

We send a GET request with curl.

PHP POST request in Laravel

In the following example, we send a POST request from an HTML form.

We validate and retrieve the POST parameters and send them in the response. This example should be tested in a browser.

In this tutorial, we have worked with GET and POST requests in plain PHP, Symfony, Slim, and Laravel.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *