HTTP REQUESTS - BASIC AUTH

Public

Using with HTTP Basic Authentication

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_...

EvanDonovan commented 5 years ago
The patch in [#82410] made it possible to use HTTP Basic Authentication with drupal_http_request(). This is especially useful when making calls to a REST API, or other web service.

The function leverages PHP's native parse_url() function in order to get the user & pass parameters needed for authentication. They are simply extracted from the URL, which should be in the format http://user:pass@example.com/end/point.php, or https://user:pass@example.com/end/point.php. If necessary, you can also append a query string to the URL.

Do not try doing the authentication adding user & pass as query string parameters because that will not work, and it will be unclear why not.

Example code for doing HTTP Basic Authentication (somewhat simplified from its original context):

Get raw version
php
  1. function get_embed_code($media_id, $width = '', $height = '') {
  2. $scheme = 'https';
  3. $user = 'api';
  4. $pass = variable_get('api_key', '');
  5. $host = 'api.example.com';
  6. $path = '/v1/medias/' . $media_id . '/embed';
  7. if(isset($width)) { $query['width'] = 'width=' . $width; }
  8. if(isset($height)) { $query['height'] = 'height=' . $height; }
  9. // Implodes the query string options with an '&'
  10. $query = implode($query, '&');
  11. // Builds the URL for drupal_http_request to use in REST API call
  12. /* Expected format: https://api:<api-key>@api.example.com/v1/medias/<media-id>/embed?width=<width>&height=<height> */
  13. $embed_url = $scheme . '://' . $user . ':' . $pass . '@' . $host . $path . '?' . $query;
  14. $result = drupal_http_request($embed_url);
  15. if(isset($result) && in_array($result->code, array('200', '302', '307')) && $result->data != '') {
  16. $embed_code = $result->data;
  17. }
  18. if(isset($embed_code) && $embed_code != '') {
  19. return $embed_code;
  20. }
  21. }
  22.  
  23. /*
  24.  In case the example above was not clear, in order to do basic auth using drupal_http_request simply enter the username and password into the url in the format below. Drupal_http_request will extract the username and password, base64 encode them and pass them along in the header appropriately
  25. */
  26.  
  27. $url = 'http://username:password@target_url.com';

function _drupal_parse_response_status

7 common.inc _drupal_parse_response_status($response)
Splits an HTTP response status line into components.

See the status line definition in RFC 2616.

Parameters

string $respone: The response status line, for example 'HTTP/1.1 500 Internal Server Error'.

Return value

array Keyed array containing the component parts. If the response is malformed, all possible parts will be extracted. 'reason_phrase' could be empty. Possible keys:

'http_version'
'response_code'
'reason_phrase'
Related topics

HTTP handling
Functions to properly handle HTTP responses.
2 calls to _drupal_parse_response_status()
DrupalHTTPResponseStatusLineTest::testStatusLine in modules/simpletest/tests/common.test
Tests parsing HTTP response status line.
drupal_http_request in includes/common.inc
Performs an HTTP request.

Get raw version
php
  1. function _drupal_parse_response_status($response) {
  2. $response_array = explode(' ', trim($response), 3);
  3. // Set up empty values.
  4. $result = array(
  5. 'reason_phrase' => '',
  6. );
  7. $result ['http_version'] = $response_array [0];
  8. $result ['response_code'] = $response_array [1];
  9. if (isset($response_array [2])) {
  10. $result ['reason_phrase'] = $response_array [2];
  11. }
  12. return $result;
  13. }

Solution for $_POST empty after drupal_http_request

http://plosquare.blogspot.com/2010/03/solution-for-post-empty-after.html

The function drupal_http_request can be used to POST data to a URL. However, what the documentation does not mention is that when you invoke it without the Content-Type header, the receiver might not see any of the posted content.

Get raw version
php
  1.  
  2. // Wrong
  3.  
  4. $result = drupal_http_request(
  5. url('some/url', array(absolute => TRUE)),
  6. array(),
  7. 'POST',
  8. 'param1=value1&param2=value2');
  9.  
  10.  
  11. // Correct:
  12.  
  13. $result = drupal_http_request(
  14. url('some/url', array(absolute => TRUE)),
  15. array('Content-Type' => 'application/x-www-form-urlencoded'),
  16. 'POST',
  17. 'param1=value1&param2=value2');

Creating $data from an array

A note about the format of posted variables (i.e. $data).

The format of the $data string should be as follows:

name1=val1&name2=val2&name3=val3

A very quick way to build that string from an array is to use http_build_query().

When calling http_build_query(), make sure the third argument is "&". Otherwise, your system may default to "&amp;" which means something completely different to the server processing the request (i.e. apple=red&amp;banana=yellow&amp;pear=green).

Get raw version
php
  1. $fruits = array('apple' => 'red', 'banana' => 'yellow', 'pear' => 'green');
  2. $data = http_build_query($fruits, '', '&');
  3.  
  4. // This will yield:
  5. // apple=red&banana=yellow&pear=green

How to pass along client/browser cookies to remote web service using drupal_http_request to share local session

The challenge here is that from the browser, we can easily see the .Net header partial serving up what it needs to, because in a direct browser connection to it, the http-get is being fetched *by the browser*. But when we want Drupal to fetch the html partial and stuff it into the header, *Drupal* doesn't know what its client browser(s) sessions are .... Ah but it does! Enter $_COOKIE.

All documentation I found on the web was about how to add cookies to a header and how to add headers to drupal_http_request. Fine and dandy, but what I was lacking was how to build a cookie from the $_COOKIE variable. Here's a complete sample snippet of code for you to work with:

Get raw version
php
  1. $cookiestring = '';
  2. foreach ($_COOKIE as $key => $cookie) {
  3. $cookiestring .= $key .'='. urlencode($cookie) .';';
  4. }
  5. print_r($_COOKIE);
  6. print_r($cookiestring);
  7. $url = 'http://www.example.com/partial';
  8. $headers = array('Cookie' => $cookiestring);
  9. $response = drupal_http_request($url, array('headers' => $headers));
  10. print_r($response);