Skip to content

Instantly share code, notes, and snippets.

@jovialcore
Last active April 13, 2023 09:47
Show Gist options
  • Save jovialcore/9b0f70be1f6d9bd2b2bf2f71faa634e4 to your computer and use it in GitHub Desktop.
Save jovialcore/9b0f70be1f6d9bd2b2bf2f71faa634e4 to your computer and use it in GitHub Desktop.
A php curl wrapper class that lets you make a post curl operation in a more elegant style.
<?php
class culrpost
{
protected $url;
protected $curl;
public $result;
// instantiates
public function __construct(string $url)
{
$this->url = $url;
$this->curlInitalize();
$this->curlSetOpt();
}
// warapper function to initalize curl as it is done natively
public function curlInitalize()
{
return $this->curl = curl_init($this->url);
}
// set the curl options
public function curlSetOpt()
{
curl_setopt($this->curl, CURLOPT_POST, true);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
return $this->curl;
}
// executing the curl
public function executeCurl(array $data)
{
//convert array data to string like name=jane&age=23
$data = http_build_query($data, '', '&', PHP_QUERY_RFC3986);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
// get the result of the curl operation
$this->result = curl_exec($this->curl);
return $this;
}
// close curl immedidtaly operations are done
public function closeCurl()
{
return curl_close($this->curl);
}
}
// how to use
$endpoint = "www.chidiebere.com/endpoint";
$curl = new culrpost($endpoint);
$data = ['name' => 'chidiebere', 'age' => '25'];
$curl->executeCurl($data)->closeCurl();
echo $curl->result; // 404 NOT FOUND --obviously because the endpoint is wrong
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment