php-guzzlePHP Guzzle post request example
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Here is an example of a POST request using Guzzle:
<?php
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"type":"User"...'
?>
The code above will send a POST request to the URL http://httpbin.org/post with the form parameters field_name, other_field, and nested_field. The response will be a status code of 200 and a content-type header of application/json; charset=utf8. The body of the response will be a JSON string.
Code explanation
$client = new GuzzleHttp\Client();- This creates a new Guzzle client object.$res = $client->request('POST', 'http://httpbin.org/post', [- This sends a POST request to the URLhttp://httpbin.org/postwith the form parameters.'form_params' => [- This is the array of form parameters that will be sent with the request.echo $res->getStatusCode();- This will output the status code of the response.echo $res->getHeaderLine('content-type');- This will output the content-type header of the response.echo $res->getBody();- This will output the body of the response.
Helpful links
More of Php Guzzle
- How to keep alive with Guzzle in PHP?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- How to set a user agent in PHP Guzzle?
- How to stream with PHP Guzzle?
- How to send multipart requests with Guzzle in PHP?
- How to use multipart/form-data with PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to send multiple requests with Guzzle in PHP?
- How to use PHP Guzzle to make a batch request?
See more codes...