Uploading Data
Guzzle provides several methods for uploading data.
You can send requests that contain a stream of data by passing a string, resource returned from fopen, or an instance of a Psr\Http\Message\StreamInterface to the body request option.
1. // Provide the body as a string.
2. $r = $client->request('POST', 'http://httpbin.org/post', [
3. 'body' => 'raw data'
4. ]);
6. // Provide an fopen resource.
7. $body = fopen('/path/to/file', 'r');
8. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
10. // Use the stream_for() function to create a PSR-7 stream.
11. $body = \GuzzleHttp\Psr7\stream_for('hello!');
12. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
An easy way to upload JSON data and set the appropriate header is using the json request option:
1. $r = $client->request('PUT', 'http://httpbin.org/put', [
2. 'json' => ['foo' => 'bar']
3. ]);
POST/Form Requests
In addition to specifying the raw data of a request using the body request option, Guzzle provides helpful abstractions over sending POST data.
Sending form fields
Sending application/x-www-form-urlencoded POST requests requires that you specify the POST fields as an array in the form_params request options.
1. $response = $client->request('POST', 'http://httpbin.org/post', [
2. 'form_params' => [
3. 'field_name' => 'abc',
4. 'other_field' => '123',
5. 'nested_field' => [
6. 'nested' => 'hello'
7. ]
8. ]
9. ]);
Sending form files
You can send files along with a form (multipart/form-data POST requests), using the multipart request option. multipart accepts an array of associative arrays, where each associative array contains the following keys:
- name: (required, string) key mapping to the form field name.
- contents: (required, mixed) Provide a string to send the contents of the file as a string, provide an fopen resource to stream the contents from a PHP stream, or provide a
Psr\Http\Message\StreamInterfaceto stream the contents from a PSR-7 stream.
1. $response = $client->request('POST', 'http://httpbin.org/post', [
2. 'multipart' => [
3. [
4. 'name' => 'field_name',
5. 'contents' => 'abc'
6. ],
7. [
8. 'name' => 'file_name',
9. 'contents' => fopen('/path/to/file', 'r')
10. ],
11. [
12. 'name' => 'other_file',
13. 'contents' => 'hello',
14. 'filename' => 'filename.txt',
15. 'headers' => [
16. 'X-Foo' => 'this is an extra header to include'
17. ]
18. ]
19. ]
20. ]);
