You are here

function flickr_curl_http_request in Flickr 7

Performs an HTTP request over cURL. Taken from http://cgit.drupalcode.org/chr/tree/chr.module.

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
4 calls to flickr_curl_http_request()
flickrcachewarmer_run in cachewarmer/flickrcachewarmer.module
Virtually visits all nodes of selected content types to ensure the cache of these pages is rebuild to avoid long page loads for a real visitor. Note that with the HEAD method the server MUST NOT return a message-body in the response. It turns out…
flickr_album in ./flickr.inc
Render multiple photos as an album.
flickr_request in ./flickr.inc
Submit a request to Flickr.
theme_flickr_photo in ./flickr.module
Theme Flickr photo.

File

./flickr.inc, line 1803
The Flickr API functions.

Code

function flickr_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' => variable_get('http_proxy'),
    'https_proxy' => variable_get('https_proxy'),
    'curl_opts' => array(),
  );

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

  // Set the proxy settings.
  flickr_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.
  flickr_curl_set_defaults($options, $ch);

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

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

  // Set request options.
  $success = flickr_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.
  flickr_curl_set_headers($options, $ch);

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

  // Make request.
  $result->data = trim(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);

  // 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.
  list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $result->data, 2);

  // 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)) {
    list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $result->data, 2);
  }
  $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 = flickr_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 = flickr_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;
  return $result;
}