You are here

private static function ShareaholicHttp::send_with_curl in Share Buttons, Related Posts, Content Analytics - Shareaholic 8

Same name and namespace in other branches
  1. 7.3 lib/social-share-counts/http.php \ShareaholicHttp::send_with_curl()
1 call to ShareaholicHttp::send_with_curl()
ShareaholicHttp::send in lib/social-share-counts/http.php
Performs a HTTP request with a url and array of options

File

lib/social-share-counts/http.php, line 53

Class

ShareaholicHttp
The purpose of this class is to provide an interface around any native http function (wp_remote_get, drupal_http_request, curl) so that one use this consistent API for making http request with well defined input and output.

Code

private static function send_with_curl($url, $options) {
  $curl_handle = curl_init($url);
  curl_setopt($curl_handle, CURLOPT_HEADER, 0);
  curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);

  // set the timeout
  $timeout = isset($options['timeout']) ? $options['timeout'] : 15;
  curl_setopt($curl_handle, CURLOPT_TIMEOUT, $timeout);

  // set the http method: default is GET
  if ($option['method'] === 'POST') {
    curl_setopt($curl_handle, CURLOPT_POST, 1);
  }

  // set the body and headers
  $headers = isset($options['headers']) ? $options['headers'] : array();
  $body = isset($options['body']) ? $options['body'] : NULL;
  if (isset($body)) {
    if (isset($headers['Content-Type']) && $headers['Content-Type'] === 'application/json') {
      $data_string = json_encode($body);
      curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string),
      ));
      curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $data_string);
    }
  }

  // set the useragent
  $useragent = isset($options['user-agent']) ? $options['user-agent'] : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0';
  curl_setopt($curl_handle, CURLOPT_USERAGENT, $useragent);

  // set the max redirects
  if (isset($options['redirection'])) {
    curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl_handle, CURLOPT_MAXREDIRS, $option['redirection']);
  }
  $output = curl_exec($curl_handle);
  $result['body'] = $output;
  $result['response'] = array(
    'code' => curl_getinfo($curl_handle, CURLINFO_HTTP_CODE),
  );
  curl_close($curl_handle);
  return $result;
}