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/post
with 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 set a user agent in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...