Search

Programming
Programming

We provide developers and engineers the guides and tutorials they...

Content
Content

Content is king. It's not just about how you're going to write, b...

Events
Events

Looking for an engaging connection with thousands of other people...

Post Multiple files with GuzzleHttp Client

Post Multiple files with GuzzleHttp Client

Guzzle is a PHP HTTP Client for sending HTTP requests to APIs. But sending multiple files with a single request sometimes bring on a lot of complexity

Guzzle is a PHP HTTP Client for sending HTTP requests to APIs. But sending multiple files with a single request sometimes bring on a lot of complexity and people get confused in sending arrays of data within an array for a multipart form, quite confusing.

This snippet will explain how to send multiple files or images with a single request through Guzzle HTTP client with ease. So let's dive straight in the code.

$output = [];
      foreach ( $images['image'] as $key => $value ) {
         if ( ! is_array( $value ) ) {
            $output[] = [
               'name'     => 'image[]',
               'contents' => fopen( $value->getPathname(), 'r' ),
               'filename' => $value->getClientOriginalName()
            ];
            continue;
         }
      }

      $output [] =
         [
            'name'     => 'field_name',
            'contents' => \request()->get( 'field_name' )
         ];

      $output [] = [
         'name'     => 'field_name_2',
         'contents' => \request()->get( 'field_name_2' )
      ];
      $output [] = [
         'name'     => 'field_name_3',
         'contents' => \request()->get( 'field_name_3' )
      ];

$client = new Client( [
   'base_uri'    => "http://api_url.dev/",
] );
 $response = $client->request( 'POST', 'api/endpoint', [
 'headers' => [
 'Authorization' => $token
 ],
 'multipart' => $output

 ] );

 $data = \GuzzleHttp\json_decode( $response->getBody() );

Try it out and let us know in the comment section if you faced any issue. Cheers!

Do follow us on Twitter.

Usama Muneer

About author

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

View all posts (110)
Your experience on this site will be improved by allowing cookies Cookie Policy