You are here

function chr_curl_http_request in cURL HTTP Request 7

Same name and namespace in other branches
  1. 6 chr.module \chr_curl_http_request()

Performs an HTTP request.

This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

Parameters

$url: A string containing a fully qualified URI.

array $options: (optional) An array that can have one or more of the following elements:

  • headers: An array containing request headers to send as name/value pairs.
  • method: A string containing the request method. Defaults to 'GET'.
  • data: A string containing the request body, formatted as 'param=value&param=value&...'. Defaults to NULL.
  • max_redirects: An integer representing how many times a redirect may be followed. Defaults to 3.
  • timeout: A float representing the maximum number of seconds the function call may take. The default is 30 seconds. If a timeout occurs, the error code is set to the HTTP_REQUEST_TIMEOUT constant.
  • context: A context resource created with stream_context_create().
  • verify_ssl: A boolean, to decide whether (TRUE) or not (FALSE) verify the SSL certificate and host.
  • verbose: A boolean, to switch on (TRUE) and off (FALSE) the cURL verbose mode.
  • cookiefile: A string containing a local path to the cookie file.
  • http_proxy: An array that will override the system-wide HTTP proxy settings. Array's elements:
  • https_proxy: An array that will override the system-wide HTTPS proxy settings.
  • curl_opts: An array of generic cURL options.

Return value

object An object that can have one or more of the following components:

  • request: A string containing the request body that was sent.
  • code: An integer containing the response status code, or the error code if an error occurred.
  • protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
  • status_message: The status message from the response, if a response was received.
  • redirect_code: If redirected, an integer containing the initial response status code.
  • redirect_url: If redirected, a string containing the URL of the redirect target.
  • error: If an error occurred, the error message. Otherwise not set.
  • errno: If an error occurred, a cURL error number greater than 0. Otherwise set to 0.
  • headers: An array containing the response headers as name/value pairs. HTTP header names are case-insensitive (RFC 2616, section 4.2), so for easy access the array keys are returned in lower case.
  • data: A string containing the response body that was received.
  • curl_opts: An array of curl options used
1 call to chr_curl_http_request()
curl_http_request in ./chr.module
Legacy wrapper callback.
2 string references to 'chr_curl_http_request'
chr_admin_settings_form_submit in ./chr.admin.inc
Submit callback
chr_enable in ./chr.install
Implements hook_enable().

File

./chr.module, line 90
cURL HTTP Request methods

Code

function chr_curl_http_request($url, array $options = array()) {
  $result = new stdClass();

  // Parse the URL and make sure we can handle the schema.
  $uri = @parse_url($url);
  if ($uri == FALSE) {
    $result->error = 'unable to parse URL';
    $result->code = -1001;
    return $result;
  }
  if (!isset($uri['scheme'])) {
    $result->error = 'missing schema';
    $result->code = -1002;
    return $result;
  }
  timer_start(__FUNCTION__);

  // Merge the default options.
  $options += array(
    'headers' => array(
      'User-Agent' => 'Drupal (+http://drupal.org/)',
    ),
    'method' => 'GET',
    'data' => NULL,
    'max_redirects' => 3,
    'timeout' => 30.0,
    'context' => NULL,
    'verify_ssl' => FALSE,
    'verbose' => FALSE,
    'cookiefile' => NULL,
    'http_proxy' => _chr_get_proxy_variable('http_proxy'),
    'https_proxy' => _chr_get_proxy_variable('https_proxy'),
    'curl_opts' => array(),
  );

  // Initialize cURL object.
  $ch = curl_init($url);

  // Set the proxy settings.
  _chr_curl_set_proxy_settings($options, $ch, $uri);

  // If the database prefix is being used by SimpleTest to run the tests in a copied
  // database then set the user-agent header to the database prefix so that any
  // calls to other Drupal pages will run the SimpleTest prefixed database. The
  // user-agent is used to ensure that multiple testing sessions running at the
  // same time won't interfere with each other as they would if the database
  // prefix were stored statically in a file or database variable.
  $test_info =& $GLOBALS['drupal_test_info'];
  if (!empty($test_info['test_run_id'])) {
    $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
  }
  elseif (empty($options['headers']['User-Agent'])) {
    $options['headers']['User-Agent'] = 'Drupal (+http://drupal.org/)';
  }

  // Set default configuration.
  _chr_curl_set_defaults($options, $ch);

  // Set cookie settings.
  _chr_curl_set_cookie_settings($options, $ch);

  // Set the port.
  $success = _chr_curl_set_port($options, $ch, $uri);
  if (FALSE === $success) {
    $result->error = 'invalid schema ' . $uri['scheme'];
    $result->code = -1003;
    return $result;
  }

  // Set request options.
  $success = _chr_curl_request_type_option($options, $ch);
  if (FALSE === $success) {
    $result->error = 'invalid method ' . $options['method'];
    $result->code = -1004;
    return $result;
  }

  // If the server URL has a user then attempt to use basic authentication.
  if (isset($uri['user'])) {
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ''));
  }

  // Set headers.
  _chr_curl_set_headers($options, $ch);

  // Set any last minute options.
  _chr_curl_set_options($options, $ch);

  // Make request.
  $result->data = ltrim(curl_exec($ch));

  // Check for errors.
  $result->errno = curl_errno($ch);

  // Get Response Info.
  $info = curl_getinfo($ch);

  // If there's been an error, do not continue.
  if ($result->errno != 0) {

    // Request timed out.
    if (CURLE_OPERATION_TIMEOUTED == $result->errno) {
      $result->code = HTTP_REQUEST_TIMEOUT;
      $result->error = 'request timed out';
      return $result;
    }
    $result->error = curl_error($ch);
    $result->code = $result->errno;
    return $result;
  }

  // The last effective URL should correspond to the Redirect URL.
  $result->redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

  // Save the request sent into the result object.
  $result->request = curl_getinfo($ch, CURLINFO_HEADER_OUT);

  // Close the connection.
  curl_close($ch);

  // For NTLM requests:
  // Since NTLM responses contain multiple header sections, we must parse them
  // differently than standard response data.
  if (isset($options['curl_opts'][CURLOPT_HTTPAUTH]) && $options['curl_opts'][CURLOPT_HTTPAUTH] & CURLAUTH_NTLM) {

    //  @todo don't need right now, fix later
    //  $result->ntlm_response = _chr_curl_parse_ntlm_response($headers);
  }

  // Parse response headers from the response body.
  // Be tolerant of malformed HTTP responses that separate header and body with
  // \n\n or \r\r instead of \r\n\r\n.
  $matches = preg_split("/\r\n\r\n|\n\n|\r\r/", $result->data, 2);
  $response = isset($matches[0]) ? $matches[0] : NULL;

  // Sometimes there isn't payload e.g. when a HEAD request is sent.
  $result->data = isset($matches[1]) ? $matches[1] : NULL;

  // Sometimes when making an HTTP request via proxy using cURL, you end up with a multiple set of headers:
  // from the web server being the actual target, from the proxy itself, etc.
  // The following 'if' statement is to check for such a situation and make sure we get a proper split between
  // actual response body and actual response headers both coming from the web server.
  while ('HTTP/' == substr($result->data, 0, 5)) {
    $matches = preg_split("/\r\n\r\n|\n\n|\r\r/", $result->data, 2);
    $response = isset($matches[0]) ? $matches[0] : NULL;

    // Sometimes there isn't payload e.g. when a HEAD request is sent.
    $result->data = isset($matches[1]) ? $matches[1] : NULL;
  }
  $response = preg_split("/\r\n|\n|\r/", $response);

  // Parse the response status line.
  list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
  $result->protocol = $protocol;
  $result->status_message = $status_message;
  $result->headers = array();

  // Parse the response headers.
  while ($line = trim(array_shift($response))) {
    list($name, $value) = explode(':', $line, 2);
    $name = strtolower($name);
    if (isset($result->headers[$name]) && $name == 'set-cookie') {

      // RFC 2109: the Set-Cookie response header comprises the token Set-
      // Cookie:, followed by a comma-separated list of one or more cookies.
      $result->headers[$name] .= ',' . trim($value);
    }
    else {
      $result->headers[$name] = trim($value);
    }
  }
  $responses = chr_response_codes();

  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  // base code in their class.
  if (!isset($responses[$code])) {
    $code = floor($code / 100) * 100;
  }
  $result->code = $code;
  switch ($code) {
    case 200:

    // OK
    case 304:

      // Not modified
      break;
    case 301:

    // Moved permanently
    case 302:

    // Moved temporarily
    case 307:

      // Moved temporarily
      $location = $result->headers['location'];
      $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
      if ($options['timeout'] <= 0) {
        $result->code = HTTP_REQUEST_TIMEOUT;
        $result->error = 'request timed out';
      }
      elseif ($options['max_redirects']) {

        // Redirect to the new location.
        $options['max_redirects']--;
        $result = chr_curl_http_request($location, $options);
        $result->redirect_code = $code;
      }
      if (!isset($result->redirect_url)) {
        $result->redirect_url = $location;
      }
      break;
    default:
      $result->error = $status_message;
  }

  // Lastly, include any cURL specific information.
  $result->curl_info = $info;

  // Debug output.
  if (variable_get('chr_debug', FALSE) and module_exists('devel')) {
    dpm($result);
  }
  return $result;
}