Sending images (upload) using Guzzle PHP HTTP client

Hey Everyone,

I was looking at my I wrote a few months ago, and I saw there was something like Guzzle. That allows you to do requests.

A was looking at my modified script that was using cURL to upload an image and downloads the return image (it is returning a URL).

public function makeCurlRequest($file)
    {
        $mime = mime_content_type($file);
        $info = pathinfo($file);
        $name = $info['basename'];
        $output = new \CURLFile($file, $mime, $name);
        $data = [
            "files" => $output,
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url . $this->quality . '&exif=' . $this->exif);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            error_log(curl_error($ch));
            return false;
        }
        curl_close($ch);
        try {
            $this->hasNoApiResponseError($result);
        } catch (Exception $e) {
            error_log($e->getMessage());
            return false;
        }
        return json_decode($result);
    }

The original was written on the resmush API page.


    $file = '/path/to/myfile.jpg';
    $mime = mime_content_type($file);
    $info = pathinfo($file);
    $name = $info['basename'];
    $output = new CURLFile($file, $mime, $name);
    $data = array(
        "files" => $output,
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://api.resmush.it/?qlty=80');
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
       $result = curl_error($ch);
    }
    curl_close ($ch);

    var_dump($result);
      

How can you do the same request using (and upload the image in the request) using guzzlephp?

You find examples when searching for “multipart” in the quickstart section of the documentation.

https://flysystem.thephpleague.com/docs/
https://flysystem.thephpleague.com/docs/guides/uploads/

When there is a library to handle these types of mundane, routine tasks it is better to use the library than write your own custom code. PHP has an outstanding ecosystem of libraries and frameworks.