Last active
February 17, 2023 16:26
-
-
Save diloabininyeri/bef044609039005bb734996fd29a36a4 to your computer and use it in GitHub Desktop.
php curl php http request class example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Http | |
{ | |
/** | |
* @var CurlHandle|false $curl | |
*/ | |
private CurlHandle|false $curl; | |
private array $curlArray = []; | |
private string|false $response; | |
public function __construct() | |
{ | |
$this->curl = curl_init(); | |
} | |
public function url(string $url): self | |
{ | |
$this->curlArray[CURLOPT_URL] = $url; | |
return $this; | |
} | |
public function timeout(int $seconds): self | |
{ | |
$this->curlArray[CURLOPT_TIMEOUT] = $seconds; | |
return $this; | |
} | |
public function acceptJson(): self | |
{ | |
$this->curlArray [CURLOPT_HTTPHEADER] = ['Content-Type: application/json']; | |
return $this; | |
} | |
public function basicAuth(string $username, string $password): self | |
{ | |
$this->curlArray [CURLOPT_USERPWD] = $username . ':' . $password; | |
return $this; | |
} | |
public function getResponse(): string|bool | |
{ | |
return $this->response; | |
} | |
public function ok(): bool | |
{ | |
return $this->status() === 200; | |
} | |
public function error() | |
{ | |
return curl_error($this->curl); | |
} | |
public function status(): int | |
{ | |
return curl_getinfo($this->curl, CURLINFO_HTTP_CODE); | |
} | |
public function close(): void | |
{ | |
curl_close($this->curl); | |
} | |
public function get(): self | |
{ | |
$this->curlArray[CURLOPT_CUSTOMREQUEST] = 'GET'; | |
$this->performRequest(); | |
return $this; | |
} | |
public function post(array $payload): self | |
{ | |
$this->curlArray [CURLOPT_CUSTOMREQUEST] = 'POST'; | |
$this->curlArray[CURLOPT_POSTFIELDS] = json_encode($payload); | |
$this->performRequest(); | |
return $this; | |
} | |
/** | |
* @return mixed | |
*/ | |
public function info(): mixed | |
{ | |
return curl_getinfo($this->curl); | |
} | |
/** | |
* @return void | |
*/ | |
private function performRequest(): void | |
{ | |
curl_setopt_array($this->curl, $this->curlArray); | |
$this->response = curl_exec($this->curl); | |
} | |
} | |
$http = new Http(); | |
$res = $http | |
->url('http://localhost/foo/bar') | |
->basicAuth('foo', 'bar') | |
->acceptJson() | |
->timeout(3) | |
->post([ | |
'transactionId' => '888fefwefe' | |
]); | |
//after request | |
$http->close(); | |
$http->ok(); | |
$http->error(); | |
$http->info(); | |
$http->status(); | |
print_r($res->getResponse()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For bearer auth , can be use