Using with HTTP Basic Authentication

Public

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):

</> CopyGet raw version
php
  1. <?php
  2. function get_embed_code($media_id, $width = '', $height = '') {
  3. $scheme = 'https';
  4. $user = 'api';
  5. $pass = variable_get('api_key', '');
  6. $host = 'api.example.com';
  7. $path = '/v1/medias/' . $media_id . '/embed';
  8. if(isset($width)) { $query['width'] = 'width=' . $width; }
  9. if(isset($height)) { $query['height'] = 'height=' . $height; }
  10. // Implodes the query string options with an '&'
  11. $query = implode($query, '&');
  12. // Builds the URL for drupal_http_request to use in REST API call
  13. /* Expected format: https://api:<api-key>@api.example.com/v1/medias/<media-id>/embed?width=<width>&height=<height> */
  14. $embed_url = $scheme . '://' . $user . ':' . $pass . '@' . $host . $path . '?' . $query;
  15. $result = drupal_http_request($embed_url);
  16. if(isset($result) && in_array($result->code, array('200', '302', '307')) && $result->data != '') {
  17. $embed_code = $result->data;
  18. }
  19. if(isset($embed_code) && $embed_code != '') {
  20. return $embed_code;
  21. }
  22. }
  23. ?>