Skip to content

Instantly share code, notes, and snippets.

@matt-allan
Last active January 7, 2016 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-allan/e6505f54fe6fd6117030 to your computer and use it in GitHub Desktop.
Save matt-allan/e6505f54fe6fd6117030 to your computer and use it in GitHub Desktop.
<?php
$stream = new GuzzleHttp\Psr7\MultipartStream([['name' => 'some-file', 'contents' => 'the contents']]);
$client = new GuzzleHttp\Client();
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $stream]);
$r->getBody()->getContents();
=> """
{\n
"args": {}, \n
"data": "", \n
"files": {}, \n
"form": {\n
"some-file": "the contents"\n
}, \n
"headers": {\n
"Content-Length": "122", \n
"Content-Type": "multipart/form-data; boundary=568daeba8d610", \n
"Host": "httpbin.org", \n
"User-Agent": "GuzzleHttp/6.1.1 curl/7.37.1 PHP/5.6.13"\n
}, \n
"json": null, \n
"origin": "72.18.228.42", \n
"url": "http://httpbin.org/post"\n
}\n
"""
>>>
@matt-allan
Copy link
Author

for 'contents' you can just pass in a stream resource instead of a string.

@judgej
Copy link

judgej commented Jan 7, 2016

As well as name and contents, there are other optional elements, such as filename and headers. The headers can be used to set Content-Type for a file, for example.

Not forgetting also that instantiating MultipartStream involves passing in multiple fields/parts, which can be a mix of text and streams.

Thanks Matthew, this is great stuff.

@judgej
Copy link

judgej commented Jan 7, 2016

What I don't understand, is how your Content-Type is being set by Guzzle. I am finding Guzzle, using PSR-7 messages does not detect the content type automatically, and does not set the Content-Type header. I am having to explicitly set the Content-Type header, which means also defining my own multipart boundary for this (Guzzle can give you the boundary it defines, but that is less portable). Are you using a stable Guzzle, or bleeding-edge dev?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment