php 47 lines · 8 steps

Uploading a file with cURL in PHP

A multipart file upload over cURL with auth headers, error handling, and JSON decoding.

Explained by highlit
1<?php
2 
3function uploadDocument(string $endpoint, string $filePath, array $meta): array
4{
5 $ch = curl_init($endpoint);
6 
7 $payload = [
8 'title' => $meta['title'],
9 'category_id' => $meta['category_id'],
10 'file' => new CURLFile($filePath, mime_content_type($filePath), basename($filePath)),
11 ];
12 
13 curl_setopt_array($ch, [
14 CURLOPT_POST => true,
15 CURLOPT_POSTFIELDS => $payload,
16 CURLOPT_RETURNTRANSFER => true,
17 CURLOPT_TIMEOUT => 30,
18 CURLOPT_HTTPHEADER => [
19 'Authorization: Bearer ' . getenv('API_TOKEN'),
20 'Accept: application/json',
21 ],
22 ]);
23 
24 $body = curl_exec($ch);
25 $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
26 
27 if ($body === false) {
28 $error = curl_error($ch);
29 curl_close($ch);
30 throw new RuntimeException("Upload request failed: {$error}");
31 }
32 
33 curl_close($ch);
34 
35 $decoded = json_decode($body, true);
36 
37 if (json_last_error() !== JSON_ERROR_NONE) {
38 throw new RuntimeException('Malformed JSON response from upload endpoint');
39 }
40 
41 if ($status >= 400) {
42 $message = $decoded['message'] ?? 'Unknown API error';
43 throw new RuntimeException("Upload rejected ({$status}): {$message}");
44 }
45 
46 return $decoded;
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1CURLFile lets cURL build a proper multipart/form-data request without hand-encoding boundaries.
  2. 2Always distinguish transport failures from HTTP-level errors — they need separate checks.
  3. 3Validate a decoded response before trusting it, since a 200 body can still be malformed JSON.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Uploading a file with cURL in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code