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
go
func UploadDocument(c *gin.Context) { fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
Handling multipart uploads in Gin
multipart-upload
validation
error-handling
Intermediate
9 steps
php
<?php namespace App\Models\Concerns;
Building soft deletes as an Eloquent trait in Laravel
traits
soft-delete
global-scope
Intermediate
10 steps
php
<?php namespace App\Services;
Idempotent role assignment in Laravel
many-to-many
pivot-data
idempotency
Intermediate
8 steps
php
<?php namespace App\Services;
Merging overlapping busy time blocks in PHP
interval-merging
sorting
datetime
Intermediate
8 steps
rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use std::sync::Arc;
Batch inserts with per-item status in Axum
batch-processing
error-handling
serde
Intermediate
8 steps
php
<?php namespace App\Listeners;
How event subscribers group listeners in Laravel
event-driven
subscribers
queues
Intermediate
6 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.