php-guzzleHow to upload a file with PHP Guzzle?
Using PHP Guzzle, you can upload a file with a POST request. The following example code will upload a file to a server:
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://example.com/upload', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen('/path/to/file', 'r')
]
]
]);
The output of the above code will be a response object containing the response from the server.
The code consists of the following parts:
- Creating a new Guzzle client:
$client = new GuzzleHttp\Client(); - Sending a POST request to the server:
$response = $client->request('POST', 'http://example.com/upload', [ - Specifying the file to upload:
'multipart' => [ [ 'name' => 'file', 'contents' => fopen('/path/to/file', 'r') ] ] - Storing the response from the server:
$response = $client->request('POST', 'http://example.com/upload', [
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
- How to install PHP Guzzle with Composer?
- How to install PHP Guzzle without Composer?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to set a timeout for a request 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 mock requests with Guzzle in PHP?
See more codes...