Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active May 22, 2025 11:18
Show Gist options
  • Save devhammed/e1fdaee69f8f7008b0ceb592c5886d7a to your computer and use it in GitHub Desktop.
Save devhammed/e1fdaee69f8f7008b0ceb592c5886d7a to your computer and use it in GitHub Desktop.
PHP Fetch
<?php
if (! class_exists('FetchResponse')) {
class FetchResponse
{
private int $status;
private string $body;
private ?string $error;
private array $headers;
public function __construct(int $status, string $body, ?string $error = null, array $headers = [])
{
$this->status = $status;
$this->body = $body;
$this->error = $error;
$this->headers = $headers;
}
public function ok(): bool
{
return $this->status >= 200 && $this->status <= 299;
}
public function status(): int
{
return $this->status;
}
public function text(): string
{
return $this->body;
}
public function json(): mixed
{
return json_decode($this->body, true);
}
public function error(): ?string
{
return $this->error;
}
public function headers(): array
{
return $this->headers;
}
public function __toString()
{
return $this->text();
}
}
}
if (! function_exists('fetch')) {
function fetch(string $url, array $options = []): FetchResponse
{
try {
$ch = curl_init();
$responseHeaders = [];
$redirect = $options['redirect'] ?? 'follow';
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => $redirect === 'follow',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HEADERFUNCTION => function ($ch, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
return $len;
}
$key = trim($header[0]);
$value = trim($header[1]);
if (!isset($responseHeaders[$key])) {
$responseHeaders[$key] = $value;
} elseif (is_array($responseHeaders[$key])) {
$responseHeaders[$key][] = $value;
} else {
$responseHeaders[$key] = [$responseHeaders[$key], $value];
}
return $len;
},
]);
// Handle method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($options['method'] ?? 'GET'));
// Headers
if (!empty($options['headers'])) {
$headers = [];
foreach ($options['headers'] as $key => $value) {
$headers[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// Body
if (!empty($options['body'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $options['body']);
}
// Execute
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
} catch (Throwable $th) {
$body = '';
$status = 0;
$error = $th->getMessage();
}
return new FetchResponse($status, $body, $error, $responseHeaders);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment