PHP possède une extension cURL pour requêter des URL.

Installation

modifier

Sur Linux :

sudo apt-get install php-curl

Exemples

modifier

Voici le POST d'un JSON avec une pièce jointe PDF (du multipart) :

    private function execCurl(
        string $method,
        string $url,
        string $token,
        string $filePath,
        string $fileName
    ): string {
        $curlFile = curl_file_create($filePath,'application/pdf', $fileName);
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => [
                'Authorization: ' . $token
            ],
            CURLOPT_POSTFIELDS => [
                'File'=> $curlFile,
                'jsondata' => '{
                    "file_name": "' . $fileName . '"
                }'
            ],
        ]);

        $response = curl_exec($curl);
        $error = curl_error($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        if (!empty($error)) {
            throw new ErrorException($status . ' ' . $error);
        }

        return $response;
    }