phpkore/src/helpers.php

51 lines
1.3 KiB
PHP

<?php
if (!function_exists('curlRequest')) {
function curlRequest(
$url,
$method = 'GET',
$queryParams = [],
$headers = [],
$body = null
): array {
$curl = curl_init();
if (!empty($queryParams)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams);
}
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => false,
];
if (!empty($body)) {
if (is_array($body)) {
$body = json_encode($body);
$headers[] = 'Content-Type: application/json';
}
$options[CURLOPT_POSTFIELDS] = $body;
}
if (!empty($headers)) {
$options[CURLOPT_HTTPHEADER] = $headers;
}
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$error = curl_error($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return [
'status' => $httpCode,
'body' => json_decode($response, true) ?? $response,
'error' => $error ?: null
];
}
}