3 * Basic Authentication provider
6 * @subpackage Authentication
10 * Basic Authentication provider
12 * Provides a handler for Basic HTTP authentication via the Authorization
16 * @subpackage Authentication
18 class Requests_Auth_Basic implements Requests_Auth {
36 * @throws Requests_Exception On incorrect number of arguments (`authbasicbadargs`)
37 * @param array|null $args Array of user and password. Must have exactly two elements
39 public function __construct($args = null) {
40 if (is_array($args)) {
41 if (count($args) !== 2) {
42 throw new Requests_Exception('Invalid number of arguments', 'authbasicbadargs');
45 list($this->user, $this->pass) = $args;
50 * Register the necessary callbacks
52 * @see curl_before_send
53 * @see fsockopen_header
54 * @param Requests_Hooks $hooks Hook system
56 public function register(Requests_Hooks &$hooks) {
57 $hooks->register('curl.before_send', array(&$this, 'curl_before_send'));
58 $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header'));
62 * Set cURL parameters before the data is sent
64 * @param resource $handle cURL resource
66 public function curl_before_send(&$handle) {
67 curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
68 curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
72 * Add extra headers to the request before sending
74 * @param string $out HTTP header string
76 public function fsockopen_header(&$out) {
77 $out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
81 * Get the authentication string (user:pass)
85 public function getAuthString() {
86 return $this->user . ':' . $this->pass;