Skip to content

Instantly share code, notes, and snippets.

@mrwadson
Last active May 22, 2023 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrwadson/1166b235a7064caa1d32ec14fce4c821 to your computer and use it in GitHub Desktop.
Save mrwadson/1166b235a7064caa1d32ec14fce4c821 to your computer and use it in GitHub Desktop.
cURL class
<?php
/*
* Usage [PHP >= 7.1]
*
require_once __DIR__ . '/Curl.php';
$curl = new Curl('https://example.com');
$curl->get();
$curl->post(['key1' => 'value1']);
try {
$res = $curl->json(['key1' => 'value1'], ['Authorization: Basic xyz_base64_string']);
} catch (JsonException $e) {
die($e->getMessage());
}
*/
class Curl
{
private $ch;
private $url;
public function __construct(string $url = null)
{
$this->url = $url;
$this->ch = curl_init($url);
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
public function get(array $query = [])
{
if ($query) {
curl_setopt($this->ch, CURLOPT_URL, $this->url . '?' . http_build_query($query));
}
$this->setOpt();
return $this->exec();
}
public function post(array $data, array $headers = [], array $options = [])
{
$this->setOpt(array_replace_recursive([
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => $headers
], $options));
return $this->exec();
}
public function json(array $data, array $headers = [], array $options = [])
{
$this->setOpt(array_replace_recursive([
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
CURLOPT_HTTPHEADER => array_merge([
'Accept: application/json',
'Content-Type: application/json'
], $headers)
], $options));
return $this->exec();
}
public function setOpt(array $options = []): void
{
/** @noinspection CurlSslServerSpoofingInspection */
curl_setopt_array($this->ch, array_replace_recursive([
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => false
], $options));
}
/** @noinspection PhpUnused */
public function getResponseCode()
{
return curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
}
private function exec()
{
if (!($result = curl_exec($this->ch))) {
throw new RuntimeException('Connection error on URL: ' . $this->url);
}
if ($errno = curl_errno($this->ch)) {
$message = curl_strerror($errno);
echo "cURL error ($errno):\n $message";
}
return $result;
}
public function __destruct()
{
curl_close($this->ch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment