Post Multiple files with GuzzleHttp Client

January 19, 2018 By - Usama Muneer | 1064

    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.

    blog user
    Usama Muneer

    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.

    Related Posts

    You developing a RESTful API on Lumen or simply require a in-memory data storage/database for quick caching purposes. Let's talk about Redis.

    This issue might have occurred while developing an application which consists of API calls at each step. Here we're concerned with VueJS Client & Laravel API, to be specific.