File Upload With Guzzle

Hi there! After a very long pause I have to say something new!

Ok, the task is to upload a file to the remote API server. Here in my project some dependencies are using Guzzle of 3.x branch, so that this tutorial is about this branch too.

The first attempt to upload the file looked as this:

<?php
$client->post( 
    '/my/great/url',
    ['Content-Type' => 'multipart/form-data'], 
    ['file' => file_get_contents($filename)] 
);

That’s wrong! Server returns “Request Too Large” error.

After a bit of struggling I found out the right approach:

<?php
$client->post(
    '/my/great/url', 
    null, 
    ['file' => '@'.$filename]
);

As you see, Guzzle is smart enough to create bunch of necessary headers. Just add ‘@’ symbol before filename to do that!

Alex Panshin avatar
About Alex Panshin
Software Engineer from Russia. Interested in PHP, Scala, microservices and Big/Fast Data stuff.
comments powered by HyperComments