php-guzzleHow to send multipart requests with Guzzle in PHP?
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. To send a multipart request with Guzzle, you need to create a multipart/form-data request.
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'other_field',
'contents' => '123'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
]
]
]);
The output of the example code will be a response object containing the response from the server.
Parts of the code:
$client = new GuzzleHttp\Client();: creates a new Guzzle client.$response = $client->request('POST', 'http://httpbin.org/post', [: sends a POST request to the specified URL.'multipart' => [: specifies that the request should be a multipart request.[: starts an array containing the fields and files to be sent.'name' => 'field_name',: specifies the name of the field.'contents' => 'abc': specifies the contents of the field.fopen('/path/to/file', 'r'): opens the file to be sent.
Helpful links
More of Php Guzzle
- How to stream with PHP Guzzle?
- How to add query parameters to a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to keep alive with Guzzle in PHP?
- How to add a bearer token in PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
- How to log requests with Guzzle in PHP?
- How to install PHP Guzzle without Composer?
- What version of PHP is required for Guzzle?
- How to update PHP Guzzle?
See more codes...