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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1CURLFile lets cURL build a proper multipart/form-data request without hand-encoding boundaries.
- 2Always distinguish transport failures from HTTP-level errors — they need separate checks.
- 3Validate a decoded response before trusting it, since a 200 body can still be malformed JSON.
Related explainers
php
<?php function buildTree(array $items, ?int $parentId = null): array {
Building a tree from a flat list in PHP
recursion
tree
grouping
Intermediate
6 steps
python
from datetime import datetime, date from decimal import Decimal from flask import Flask, jsonify from flask.json.provider import DefaultJSONProvider
Serializing SQLAlchemy models in Flask JSON
serialization
orm
json
Intermediate
6 steps
php
final class ConfigResolver { private array $merged;
Layered config merging in PHP
recursion
immutability
variadics
Intermediate
8 steps
javascript
const express = require('express'); const compression = require('compression'); const zlib = require('zlib');
Tuning Express response compression
compression
middleware
http
Intermediate
9 steps
typescript
type Event = Record<string, unknown>; interface BatcherOptions { endpoint: string;
Batching analytics events in TypeScript
batching
buffering
async
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Streaming CSV imports in Laravel
lazy-evaluation
generators
batch-processing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/uploading-a-file-with-curl-in-php-explained-php-d54b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.