Basic.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Basic Authentication provider
  4. *
  5. * @package Requests
  6. * @subpackage Authentication
  7. */
  8. /**
  9. * Basic Authentication provider
  10. *
  11. * Provides a handler for Basic HTTP authentication via the Authorization
  12. * header.
  13. *
  14. * @package Requests
  15. * @subpackage Authentication
  16. */
  17. class Requests_Auth_Basic implements Requests_Auth {
  18. /**
  19. * Username
  20. *
  21. * @var string
  22. */
  23. public $user;
  24. /**
  25. * Password
  26. *
  27. * @var string
  28. */
  29. public $pass;
  30. /**
  31. * Constructor
  32. *
  33. * @throws Requests_Exception On incorrect number of arguments (`authbasicbadargs`)
  34. * @param array|null $args Array of user and password. Must have exactly two elements
  35. */
  36. public function __construct($args = null) {
  37. if (is_array($args)) {
  38. if (count($args) !== 2) {
  39. throw new Requests_Exception('Invalid number of arguments', 'authbasicbadargs');
  40. }
  41. list($this->user, $this->pass) = $args;
  42. }
  43. }
  44. /**
  45. * Register the necessary callbacks
  46. *
  47. * @see curl_before_send
  48. * @see fsockopen_header
  49. * @param Requests_Hooks $hooks Hook system
  50. */
  51. public function register(Requests_Hooks &$hooks) {
  52. $hooks->register('curl.before_send', array(&$this, 'curl_before_send'));
  53. $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header'));
  54. }
  55. /**
  56. * Set cURL parameters before the data is sent
  57. *
  58. * @param resource $handle cURL resource
  59. */
  60. public function curl_before_send(&$handle) {
  61. curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  62. curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
  63. }
  64. /**
  65. * Add extra headers to the request before sending
  66. *
  67. * @param string $out HTTP header string
  68. */
  69. public function fsockopen_header(&$out) {
  70. $out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
  71. }
  72. /**
  73. * Get the authentication string (user:pass)
  74. *
  75. * @return string
  76. */
  77. public function getAuthString() {
  78. return $this->user . ':' . $this->pass;
  79. }
  80. }