You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.4 KiB

  1. <?php
  2. namespace request;
  3. function get_url($url, $include_headers=false) {
  4. $ch = curl_init($url);
  5. set_user_agent($ch);
  6. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  8. if($include_headers) {
  9. curl_setopt($ch, CURLOPT_HEADER, true);
  10. $response = curl_exec($ch);
  11. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  12. return [
  13. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  14. 'headers' => trim(substr($response, 0, $header_size)),
  15. 'body' => substr($response, $header_size)
  16. ];
  17. } else {
  18. return curl_exec($ch);
  19. }
  20. }
  21. function get_head($url) {
  22. $ch = curl_init($url);
  23. set_user_agent($ch);
  24. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  25. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  26. curl_setopt($ch, CURLOPT_HEADER, true);
  27. curl_setopt($ch, CURLOPT_NOBODY, true);
  28. $headers = curl_exec($ch);
  29. return [
  30. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  31. 'headers' => trim($headers)
  32. ];
  33. }
  34. function post($url, $params, $format='form') {
  35. $ch = curl_init($url);
  36. set_user_agent($ch);
  37. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  38. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  39. if($format == 'json') {
  40. $body = json_encode($params);
  41. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  42. } else {
  43. $body = http_build_query($params);
  44. }
  45. curl_setopt($ch, CURLOPT_POST, true);
  46. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  47. curl_setopt($ch, CURLOPT_HEADER, true);
  48. $response = curl_exec($ch);
  49. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  50. return [
  51. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  52. 'headers' => trim(substr($response, 0, $header_size)),
  53. 'body' => substr($response, $header_size)
  54. ];
  55. }
  56. function set_user_agent(&$ch) {
  57. // Unfortunately I've seen a bunch of websites return different content when the user agent is set to something like curl or other server-side libraries, so we have to pretend to be a browser to successfully get the real HTML
  58. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) p3k/Switchboard/0.1.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36');
  59. }
  60. function response_is($status, $prefix) {
  61. if($status) {
  62. $status_str = (string)$status;
  63. return $status_str[0] == (string)$prefix;
  64. } else {
  65. return false;
  66. }
  67. }