Language:

Search

Handling file Inputs in PHP with CURL

  • Share this:
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.

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.

Usama Muneer

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.