3 * HTTP Proxy connection interface
11 * HTTP Proxy connection interface
13 * Provides a handler for connection via an HTTP proxy
19 class Requests_Proxy_HTTP implements Requests_Proxy {
23 * Notation: "host:port" (eg 127.0.0.1:8080 or someproxy.com:3128)
44 * Do we need to authenticate? (ie username & password have been provided)
48 public $use_authentication;
54 * @throws Requests_Exception On incorrect number of arguments (`authbasicbadargs`)
55 * @param array|null $args Array of user and password. Must have exactly two elements
57 public function __construct($args = null) {
58 if (is_string($args)) {
61 elseif (is_array($args)) {
62 if (count($args) == 1) {
63 list($this->proxy) = $args;
65 elseif (count($args) == 3) {
66 list($this->proxy, $this->user, $this->pass) = $args;
67 $this->use_authentication = true;
70 throw new Requests_Exception('Invalid number of arguments', 'proxyhttpbadargs');
76 * Register the necessary callbacks
79 * @see curl_before_send
80 * @see fsockopen_remote_socket
81 * @see fsockopen_remote_host_path
82 * @see fsockopen_header
83 * @param Requests_Hooks $hooks Hook system
85 public function register(Requests_Hooks &$hooks) {
86 $hooks->register('curl.before_send', array(&$this, 'curl_before_send'));
88 $hooks->register('fsockopen.remote_socket', array(&$this, 'fsockopen_remote_socket'));
89 $hooks->register('fsockopen.remote_host_path', array(&$this, 'fsockopen_remote_host_path'));
90 if ($this->use_authentication) {
91 $hooks->register('fsockopen.after_headers', array(&$this, 'fsockopen_header'));
96 * Set cURL parameters before the data is sent
99 * @param resource $handle cURL resource
101 public function curl_before_send(&$handle) {
102 curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
103 curl_setopt($handle, CURLOPT_PROXY, $this->proxy);
105 if ($this->use_authentication) {
106 curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
107 curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string());
112 * Alter remote socket information before opening socket connection
115 * @param string $remote_socket Socket connection string
117 public function fsockopen_remote_socket(&$remote_socket) {
118 $remote_socket = $this->proxy;
122 * Alter remote path before getting stream data
125 * @param string $path Path to send in HTTP request string ("GET ...")
126 * @param string $url Full URL we're requesting
128 public function fsockopen_remote_host_path(&$path, $url) {
133 * Add extra headers to the request before sending
136 * @param string $out HTTP header string
138 public function fsockopen_header(&$out) {
139 $out .= sprintf("Proxy-Authorization: Basic %s\r\n", base64_encode($this->get_auth_string()));
143 * Get the authentication string (user:pass)
148 public function get_auth_string() {
149 return $this->user . ':' . $this->pass;