PHP cURL POST Request with JSON Data and Headers
Owner: SnippetBot
Created: 2026-10-09 00:00:39
Size: 2.36 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
function postJsonToApi(string $url, array $data, array $headers = []): ?array
{
$jsonData = json_encode($data);
if ($jsonData === false) {
error_log("Failed to encode JSON data for URL: " . $url);
return null;
}
// Default headers
$defaultHeaders = [
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData),
// Add Authorization header if needed, e.g.:
// 'Authorization: Bearer YOUR_API_KEY_HERE'
];
// Merge custom headers, allowing overrides
$mergedHeaders = array_merge($defaultHeaders, $headers);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1); // Set as POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // Set JSON data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, $mergedHeaders); // Set headers
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
error_log("cURL Error for URL {$url}: {$error_msg}");
curl_close($ch);
return null;
}
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300) {
return json_decode($response, true);
} else {
error_log("API call to {$url} failed with HTTP code {$httpCode}. Response: {$response}");
return null;
}
}
// Example Usage:
// $apiUrl = "https://api.example.com/create-resource"; // Replace with your API endpoint
// $postData = [
// 'name' => 'New Item',
// 'description' => 'This is a description for the new item.',
// 'quantity' => 10
// ];
// $customHeaders = [
// 'X-Custom-Header: MyValue',
// 'Authorization: Bearer YOUR_ACTUAL_API_KEY' // Replace with your actual key
// ];
// $result = postJsonToApi($apiUrl, $postData, $customHeaders);
// if ($result) {
// echo "Resource created successfully:
";
// print_r($result);
// } else {
// echo "Failed to create resource.
";
// }
// You can test with a public API like httpbin.org for POST requests:
// $testApiUrl = "https://httpbin.org/post";
// $testData = ['message' => 'Hello from PHP cURL', 'timestamp' => time()];
// $testResult = postJsonToApi($testApiUrl, $testData);
// if ($testResult) {
// echo "
Test API call result:
";
// print_r($testResult);
// }
?>