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...

Handling file Inputs in PHP with CURL

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.

Tax Calculator: Belgium Tax Calculator

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).

Tax Calculator: Denmark Tax Calculator

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.

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