Skip to content

Instantly share code, notes, and snippets.

@mdelano
Created November 10, 2014 13:14
Show Gist options
  • Save mdelano/59f4de483b81e530a680 to your computer and use it in GitHub Desktop.
Save mdelano/59f4de483b81e530a680 to your computer and use it in GitHub Desktop.
An example showing how to create an invoke an HTTP client in PHP using cUrl, POST, and Basic Auth
/************************************
*
* This part of the example is the HTTP
* client responsible for making the request
*
*************************************/
<?php
class WebClient {
private $username;
private $password;
// Create a new web client by passing in the credentials for basic auth
function __construct($username, $password)
{
$this->username = $username;
$this->password = $password
}
public function post($url, $payload) {
$curl = curl_init();
// Setup the request
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => $this->getRequestHeaders(),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => "TreenoHRCorpWeb/1.0; +http://www.treenohr.com" // Make sure the treenohr web servers know who we are
));
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
private function getRequestHeaders() {
$headers = array("Content-Type: application/json; charset=utf-8","Accept:application/json");
authHeader = "Authorization: Basic ".base64_encode($this->username.":".$this->password);
array_push($headers, $authHeader);
return $headers;
}
}
/************************************
*
* This part of the example shows how
* to call the above http client
*
*************************************/
<?php
use <PATH TO WebClient.php>\WebClient;
$username = "<YOUR USERNAME>";
$password = "<YOUR PASSWORD>";
// Instantiate client
try {
var $webClient = new WebClient();
$webClient->post("http://<TREENOWEBHOST>/api/accountscaffolding", "{ \"DomainName\":\"<NEW DOMAIN>\"}")
}
catch(\mediasilo\http\exception\NotAuthenticatedException $e) {
print "Something went wrong. Cat on the keyboard? \n";
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment