How to catch cURL errors in php
While working with API request using PHP cURL request, you might get null response in curl request. This is because your cURL request failed due to error.
In PHP curl there is curl_error()
function which catch the error. Here is example code for cURL error.
<?php
$url = 'https://hackthestuff.com/api/request';
$data = [
'name' => 'Hackthestuff',
'email' => '[email protected]'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// required for HTTP error codes to be reported
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
// echo($error_msg);
}
Copyright 2023 HackTheStuff