Class-CurlFetchWeb.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. /**
  3. * Simple cURL class to fetch a web page
  4. * Properly redirects even with safe mode and basedir restrictions
  5. * Can provide simple post options to a page
  6. *
  7. * Load class
  8. * Initiate as
  9. * - $fetch_data = new cURL_fetch_web_data();
  10. * - optionaly pass an array of cURL options and redirect count
  11. * - cURL_fetch_web_data(cURL options array, Max redirects);
  12. * - $fetch_data = new cURL_fetch_web_data(array(CURLOPT_SSL_VERIFYPEER => 1), 5);
  13. *
  14. * Make the call
  15. * - $fetch_data('http://www.simplemachines.org'); // fetch a page
  16. * - $fetch_data('http://www.simplemachines.org', array('user' => 'name', 'password' => 'password')); // post to a page
  17. * - $fetch_data('http://www.simplemachines.org', parameter1&parameter2&parameter3); // post to a page
  18. *
  19. *
  20. * Get the data
  21. * - $fetch_data->result('body'); // just the page content
  22. * - $fetch_data->result(); // an array of results, body, header, http result codes
  23. * - $fetch_data->result_raw(); // show all results of all calls (in the event of a redirect)
  24. * - $fetch_data->result_raw(0); // show all results of call x
  25. *
  26. */
  27. if (!defined('SMF'))
  28. die('Hacking attempt...');
  29. class curl_fetch_web_data
  30. {
  31. private $default_options = array(
  32. CURLOPT_RETURNTRANSFER => 1, // Get returned value as a string (don't output it)
  33. CURLOPT_HEADER => 1, // We need the headers to do our own redirect
  34. CURLOPT_FOLLOWLOCATION => 0, // Don't follow, we will do it ourselves so safe mode and open_basedir will dig it
  35. CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0', // set a normal looking useragent
  36. CURLOPT_CONNECTTIMEOUT => 15, // Don't wait forever on a connection
  37. CURLOPT_TIMEOUT => 90, // A page should load in this amount of time
  38. CURLOPT_MAXREDIRS => 5, // stop after this many redirects
  39. CURLOPT_ENCODING => 'gzip,deflate', // accept gzip and decode it
  40. CURLOPT_SSL_VERIFYPEER => 0, // stop cURL from verifying the peer's certificate
  41. CURLOPT_SSL_VERIFYHOST => 0, // stop cURL from verifying the peer's host
  42. CURLOPT_POST => 0, // no post data unless its passed
  43. );
  44. /**
  45. * Start the curl object
  46. * - allow for user override values
  47. *
  48. * @param type $options, cURL options as an array
  49. * @param type $max_redirect, use to overide the default of 3
  50. */
  51. public function __construct($options = array(), $max_redirect = 3)
  52. {
  53. // Initialize class variables
  54. $this->max_redirect = intval($max_redirect);
  55. $this->user_options = $options;
  56. }
  57. /**
  58. * Main calling function,
  59. * - will request the page data from a given $url
  60. * - optionally will post data to the page form if post data is supplied
  61. * - passed arrays will be converted to a post string joined with &'s
  62. * - calls set_options to set the curl opts array values based on the defaults and user input
  63. *
  64. * @param type $url, the site we are going to fetch
  65. * @param type $post_data, any post data as form name => value
  66. */
  67. public function get_url_data($url, $post_data = array())
  68. {
  69. // POSTing some data perhaps?
  70. if (!empty($post_data) && is_array($post_data))
  71. $this->post_data = $this->build_post_data($post_data);
  72. elseif (!empty($post_data))
  73. $this->post_data = trim($post_data);
  74. // set the options and get it
  75. $this->set_options();
  76. $this->curl_request(str_replace(' ', '%20', $url));
  77. }
  78. /**
  79. * Makes the actual cURL call
  80. * - stores responses (url, code, error, headers, body) in the response array
  81. * - detects 301, 302, 307 codes and will redirect to the given response header location
  82. *
  83. * @param type $url, site to fetch
  84. * @param type $redirect, flag to indicate if this was a redirect request or not
  85. * @return boolean
  86. */
  87. private function curl_request($url, $redirect = false)
  88. {
  89. // we do have a url I hope
  90. if ($url == '')
  91. return false;
  92. else
  93. $this->options[CURLOPT_URL] = $url;
  94. // if we have not already been redirected, set it up so we can if needed
  95. if (!$redirect)
  96. {
  97. $this->current_redirect = 1;
  98. $this->response = array();
  99. }
  100. // Initialize the curl object and make the call
  101. $cr = curl_init();
  102. curl_setopt_array($cr, $this->options);
  103. curl_exec($cr);
  104. // Get what was returned
  105. $curl_info = curl_getinfo($cr);
  106. $curl_content = curl_multi_getcontent($cr);
  107. $url = $curl_info['url']; // Last effective URL
  108. $http_code = $curl_info['http_code']; // Last HTTP code
  109. $body = (!curl_error($cr)) ? substr($curl_content, $curl_info['header_size']) : false;
  110. $error = (curl_error($cr)) ? curl_error($cr) : false;
  111. // close this request
  112. curl_close($cr);
  113. // store this 'loops' data, someone may want all of these :O
  114. $this->response[] = array(
  115. 'url' => $url,
  116. 'code' => $http_code,
  117. 'error' => $error,
  118. 'headers' => isset($this->headers) ? $this->headers : false,
  119. 'body' => $body,
  120. );
  121. // If this a redirect with a location header and we have not given up, then do it again
  122. if (preg_match('~30[127]~i', $http_code) === 1 && $this->headers['location'] != '' && $this->current_redirect <= $this->max_redirect)
  123. {
  124. $this->current_redirect++;
  125. $header_location = $this->get_redirect_url($url, $this->headers['location']);
  126. $this->redirect($header_location, $url);
  127. }
  128. }
  129. /**
  130. * Used if being redirected to ensure we have a fully qualified address
  131. *
  132. * @param type $last_url, where we went to
  133. * @param type $new_url, where we were redirected to
  134. * @return new url location
  135. */
  136. private function get_redirect_url($last_url = '', $new_url = '')
  137. {
  138. // Get the elements for these urls
  139. $last_url_parse = parse_url($last_url);
  140. $new_url_parse = parse_url($new_url);
  141. // redirect headers are often incomplete or relative so we need to make sure they are fully qualified
  142. $new_url_parse['scheme'] = isset($new_url_parse['scheme']) ? $new_url_parse['scheme'] : $last_url_parse['scheme'];
  143. $new_url_parse['host'] = isset($new_url_parse['host']) ? $new_url_parse['host'] : $last_url_parse['host'];
  144. $new_url_parse['path'] = isset($new_url_parse['path']) ? $new_url_parse['path'] : $last_url_parse['path'];
  145. $new_url_parse['query'] = isset($new_url_parse['query']) ? $new_url_parse['query'] : '';
  146. // Build the new URL that was in the http header
  147. return $new_url_parse['scheme'] . '://' . $new_url_parse['host'] . $new_url_parse['path'] . (!empty($new_url_parse['query']) ? '?' . $new_url_parse['query'] : '');
  148. }
  149. /**
  150. * Used to return the results to the calling program
  151. * - called as ->result() will return the full final array
  152. * - called as ->result('body') to just return the page source of the result
  153. *
  154. * @param type $area, used to return an area such as body, header, error
  155. * @return type
  156. */
  157. public function result($area = '')
  158. {
  159. $max_result = count($this->response) - 1;
  160. // just return a specifed area or the entire result?
  161. if ($area == '')
  162. return $this->response[$max_result];
  163. else
  164. return isset($this->response[$max_result][$area]) ? $this->response[$max_result][$area] : $this->response[$max_result];
  165. }
  166. /**
  167. * Will return all results from all loops (redirects)
  168. * - Can be call as ->result_raw(x) where x is a specific loop results.
  169. * - Call as ->result_raw() for everything.
  170. *
  171. * @param type $response_number
  172. * @return type
  173. */
  174. public function result_raw($response_number = '')
  175. {
  176. if (!is_numeric($response_number))
  177. return $this->response;
  178. else
  179. {
  180. $response_number = min($response_number, count($this->response) - 1);
  181. return $this->response[$response_number];
  182. }
  183. }
  184. /**
  185. * Takes supplied POST data and url encodes it
  186. * - forms the date (for post) in to a string var=xyz&var2=abc&var3=123
  187. * - drops vars with @ since we don't support sending files (uploading)
  188. *
  189. * @param type $post_data
  190. * @return type
  191. */
  192. private function build_post_data($post_data)
  193. {
  194. if (is_array($post_data))
  195. {
  196. $postvars = array();
  197. // build the post data, drop ones with leading @'s since those can be used to send files, we don't support that.
  198. foreach ($post_data as $name => $value)
  199. $postvars[] = $name . '=' . urlencode($value[0] == '@' ? '' : $value);
  200. return implode('&', $postvars);
  201. }
  202. else
  203. return $post_data;
  204. }
  205. /**
  206. * Sets the final cURL options for the current call
  207. * - overwrites our default values with user supplied ones or appends new user ones to what we have
  208. * - sets the callback function now that $this is existing
  209. *
  210. */
  211. private function set_options()
  212. {
  213. // Callback to parse the returned headers, if any
  214. $this->default_options[CURLOPT_HEADERFUNCTION] = array($this, 'header_callback');
  215. // Any user options to account for
  216. if (is_array($this->user_options))
  217. {
  218. $keys = array_merge(array_keys($this->default_options), array_keys($this->user_options));
  219. $vals = array_merge($this->default_options, $this->user_options);
  220. $this->options = array_combine($keys, $vals);
  221. }
  222. else
  223. $this->options = $this->default_options;
  224. // POST data options, here we don't allow any overide
  225. if (isset($this->post_data))
  226. {
  227. $this->options[CURLOPT_POST] = 1;
  228. $this->options[CURLOPT_POSTFIELDS] = $this->post_data;
  229. }
  230. }
  231. /**
  232. * Called to initiate a redirect from a 301, 302 or 307 header
  233. * - resets the cURL options for the loop, sets the referrer flag
  234. *
  235. * @param type $target_url
  236. * @param type $referer_url
  237. */
  238. private function redirect($target_url, $referer_url)
  239. {
  240. // no no I last saw that over there ... really, 301, 302, 307
  241. $this->set_options();
  242. $this->options[CURLOPT_REFERER] = $referer_url;
  243. $this->curl_request($target_url, true);
  244. }
  245. /**
  246. * Callback function to parse returned headers
  247. * - lowercases everything to make it consistent
  248. *
  249. * @param type $cr
  250. * @param type $header
  251. * @return type
  252. */
  253. private function header_callback($cr, $header)
  254. {
  255. $_header = trim($header);
  256. $temp = explode(': ', $_header, 2);
  257. // set proper headers only
  258. if (isset($temp[0]) && isset($temp[1]))
  259. $this->headers[strtolower($temp[0])] = strtolower(trim($temp[1]));
  260. // return the length of what was passed unless you want a Failed writing header error ;)
  261. return strlen($header);
  262. }
  263. }
  264. ?>