Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save maitret/2877b8b6ad73f46d906aa4055c4ae621 to your computer and use it in GitHub Desktop.
Save maitret/2877b8b6ad73f46d906aa4055c4ae621 to your computer and use it in GitHub Desktop.
PHP cURL request multipart/form-data #php #curl #request #multipart #formdata #file #upload
$ch = curl_init();

$headers   = array();
$headers[] = "Authorization: Bearer " . $apiToken;
//$headers[] = "Content-Type: multipart/form-data";     // ERROR: no uses esta cabecera. Si $post es un array, la cabecera se añade automáticamente. Si se añade manualmente, me ha pasado que el boundary o el base64 se genera mal.

$cfile = new \CURLFile($fileNameWithFullPath);

//$post = array($fieldName => '@/tmp/phpDT8j');         // ERROR: no uses '@'. Genera errores en el base64. Desde PHP 5.5 está obsoleto. En su lugar usar CURLFile.
$post = array($fieldName => $cfile);                    // e.g. $fieldName = 'image'

curl_setopt_array(
    $ch,
    [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_URL            => $url,
        CURLOPT_POSTFIELDS     => $post,
        
        // CURLOPT_POST           => true,              // ERROR: no uses esta opción. El método se asigna a POST automáticamente cuando usas CURLOPT_POSTFIELDS. Si se usa y el Content-Type es multipart/form-data, el archivo no se sube y se envía un payload vacío. Úsalo solo cuando es un x-www-form-urlencoded.
        // CURLOPT_PROXY          => 'localhost:8080',  // Úsalo para depurar! Usar un proxy como Burp Suite te ayuda muchísimo para saber qué request le llega al servidor (en caso de que te sea imposible depurarlo)
        // CURLOPT_SSL_VERIFYPEER => false,             // Esta opción, también para el proxy, se usa para ignorar los certificados en una conexión https que pasa por un proxy
    ]
);

$result   = curl_exec($ch);                             // Si el código http de la response es 400+, aquí llega el payload de error de la response
$response = curl_getinfo($ch);                          // Aquí se recogen todas las cabeceras de la response. Solo se recogen las cabeceras si se ha asignado CURLOPT_RETURNTRANSFER a true

curl_close($ch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment