Convert curl command to Guzzle psr7 http

863 Views Asked by At

I need to convert this cURL command to php:

curl -X POST https://google.com \
-H 'custom_id: 1234' \
--form 'file=@"/Desktop/image.jpg"' \
--form 'options_json="{\"rm_spaces\": true}"'

I have tried something like this:

<?php

use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Psr7\Utils;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;

final class CurlCommand
{
    private RequestFactoryInterface $requestFactory;

    private ClientInterface $httpClient;

    private StreamFactoryInterface $streamFactory;

    private UriFactoryInterface $uriFactory;

    public function curl(): void
    {
        $createUri = $this->uriFactory->createUri('https://google.com');

        $jsonData = [
            "multipart" => [
                [
                    'name'     => 'image.jpg',
                    'contents' => Utils::tryFopen('/Desktop/image.jpg', 'r')
                ],
            ]
        ];

        $request = $this->requestFactory->createRequest('POST', $createUri)
            ->withHeader('custom_id', '1234')
            ->withBody($this->streamFactory->createStream(json_encode($jsonData)));
            
        $response = $this->httpClient->sendRequest($request);
    }
}

But the file is not attached as form-data I am using a guzzle for psr7.

Thanks in advance for the help! I could not find any information in guzzle documentation, because as you can see I am working on interfaces.

1

There are 1 best solutions below

0
On

use this

Laravel 8 You May Easy Call Multipart Api for image uploading directly using use GuzzleHttp\Client;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
use File;

        $filename = $req->file('file1')->getClientOriginalName();
        $getfilePath  = $req->file('file1')->getRealPath();
        $client = new Client();
$response = $client->request('POST', 'http://127.0.0.1:8045/api/uploadImages', [
    'multipart' => [
        [
            'name'     => 'image',
            'contents' => fopen($getfilePath, 'r')
        ],
        // 'headers'  => [
        //      'Content-Type' => '<Content-type header>'
        //  ]
       
    ]
]);
echo $response->getStatusCode();
$bodyresponcs = $response->getBody();
$result = json_decode($bodyresponcs);
print_r($result->status);