PHP

cURL Multipart File Upload

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Upload one or more files via multipart/form-data using cURL's CURLFile abstraction. No manual boundary or body construction needed.
PHP
Raw
<?php
function uploadFiles(string $url, array $files, array $fields = []): string {
    $payload = $fields;
    foreach ($files as $name => $path) {
        $mime = (new finfo(FILEINFO_MIME_TYPE))->file($path);
        $payload[$name] = new CURLFile($path, $mime ?: 'application/octet-stream', basename($path));
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 60,
    ]);
    $resp = curl_exec($ch);
    if ($resp === false) throw new RuntimeException('Upload failed: ' . curl_error($ch));
    curl_close($ch);
    return $resp;
}

$resp = uploadFiles('https://api.example.com/avatar', ['avatar' => '/tmp/pic.png'], ['user_id' => '42']);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.