phpkore/src/helpers.php

52 lines
1.3 KiB
PHP
Raw Normal View History

2025-06-13 14:09:31 -03:00
<?php
if (!function_exists('curlRequest')) {
function curlRequest(
2025-07-04 11:45:50 -03:00
$url,
$method = 'GET',
$queryParams = [],
$headers = [],
$body = null
2025-06-13 14:09:31 -03:00
): array {
$curl = curl_init();
if (!empty($queryParams)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams);
}
2025-06-24 14:41:29 -03:00
2025-06-13 14:09:31 -03:00
$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;
}
2025-06-24 14:41:29 -03:00
2025-06-13 14:09:31 -03:00
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
];
}
}