cURL permette di effettuare richieste HTTP da PHP.
GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);POST request
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.example.com/create",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["name" => "Test"]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer $token"
]
]);
$response = curl_exec($ch);Gestione errori
if (curl_errno($ch)) {
echo "Errore: " . curl_error($ch);
}