Handling file Inputs in PHP with CURL

Handling files while working with APIs are always a pain. While working with API calls, the most common solution is cURL for sure for requesting & receiving data through the valid endpoints.

Handling files while working with APIs are always a pain. While working with API calls, the most common solution is cURL for sure for requesting & receiving data through the valid endpoints.

You may also like

Snippet

      $file      = Input::file( 'file_name' );
      $imagePath = $file->getPathName();

      $tmp = tempnam( sys_get_temp_dir(), 'php' );
      file_put_contents( $tmp, file_get_contents( $imagePath ) );

      $curl = curl_init();

      curl_setopt( $curl, CURLOPT_URL, 'mydomain.com/api/endpoint' );

      curl_setopt( $curl, CURLOPT_VERBOSE, 1 );

      curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 1 );

      // sending file
      curl_setopt( $curl, CURLOPT_POST, true );
      curl_setopt( $curl,
         CURLOPT_HTTPHEADER, array(
            "authorization: Bearer " . $token
         ) );

      curl_setopt(
         $curl,
         CURLOPT_POSTFIELDS,
         array(
            'file_name' => $tmp,
         ) );

      // outputting the response
      curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
      $result = curl_exec( $curl );

      unlink( $tmp ); // removing temp file
      curl_close( $curl );

      $results = json_decode( $result );

Conclusion

The above piece of code is tested & works just fine. You just need to replace your image name, API endpoint & token (if required).

Doesn’t like this approach? You may also read on how to handle file inputs in PHP with GuzzleHTTP Client.

Try it out yourself & leave us a comment in the below section if you got stuck in between. We’d love to help out.

Do follow us on Twitter.