php-guzzleHow to use multipart/form-data with PHP Guzzle?
Using multipart/form-data with PHP Guzzle is easy. Here is an example code block to demonstrate how to do it:
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
]
]
]);
The output of the example code will be a response object containing the data sent in the request.
Code explanation
$client = new GuzzleHttp\Client();
- creates a new Guzzle client object$response = $client->request('POST', 'http://httpbin.org/post', [
- sends a POST request to the specified URL'multipart' => [
- specifies that the request should use multipart/form-data[
- starts an array of data to be sent in the request'name' => 'field_name',
- specifies the name of the field'contents' => 'abc'
- specifies the contents of the fieldfopen('/path/to/file', 'r')
- opens the file to be sent in the request]);
- ends the array of data to be sent in the request
Helpful links
More of Php Guzzle
- How to use PHP Guzzle to make a batch request?
- How to set a user agent in PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- What version of PHP is required for Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to set a timeout for a request with PHP Guzzle?
- How to add a bearer token in PHP Guzzle?
- How to add an authorization header bearer in PHP Guzzle?
- How to update PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
See more codes...