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 use PHP Guzzle to make a batch request?
- How to send multipart requests with Guzzle in PHP?
- How to update PHP Guzzle?
- How to post form data with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- What version of PHP is required for Guzzle?
- How to use a proxy with Guzzle in PHP?
- PHP Guzzle get request example
- How to use cookies with Guzzle in PHP?
- How to set a user agent in PHP Guzzle?
See more codes...