Util.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. class Qihoo_Util
  3. {
  4. const METHOD_GET = 'GET';
  5. const METHOD_POST = 'POST';
  6. const USERAGENT = 'MSDK_PHP_v0.0.5(20140218)';
  7. private static $err;
  8. public static function requestUrl($url)
  9. {
  10. return file_get_contents($url);
  11. }
  12. public static function getSign($params, $appSecret)
  13. {
  14. unset($params['sign']);
  15. unset($params['sign_return']);
  16. $processedParams = array();
  17. foreach ($params as $k => $v) {
  18. if (empty($v)) {
  19. continue;
  20. }
  21. $processedParams[$k] = $v;
  22. }
  23. ksort($processedParams);
  24. $signStr = join('#', $processedParams) . '#' . $appSecret;
  25. return md5($signStr);
  26. }
  27. private static $_followRedirect = false;
  28. public static function setFollowRedirect($val)
  29. {
  30. self::$_followRedirect = $val;
  31. }
  32. public static function request($url, $mode, $params = '', $needHeader = false, $timeout = 10)
  33. {
  34. self::$err = null;
  35. $ch = curl_init();
  36. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  37. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  38. curl_setopt($ch, CURLOPT_USERAGENT, self::USERAGENT);
  39. curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
  40. if (self::$_followRedirect) {
  41. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  42. }
  43. if ($needHeader) {
  44. curl_setopt($ch, CURLOPT_HEADER, true);
  45. }
  46. if ($mode == 'POST') {
  47. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
  48. curl_setopt($ch, CURLOPT_POST, true);
  49. if (is_array($params)) {
  50. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
  51. } else {
  52. curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  53. }
  54. } else {
  55. if (is_array($params)) {
  56. $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
  57. } else {
  58. $url .= (strpos($url, '?') === false ? '?' : '&') . $params;
  59. }
  60. }
  61. curl_setopt($ch, CURLOPT_URL, $url);
  62. $result = curl_exec($ch);
  63. if ($needHeader) {
  64. $tmp = $result;
  65. $result = array();
  66. $info = curl_getinfo($ch);
  67. $result['header'] = substr($tmp, 0, $info['header_size']);
  68. $result['body'] = trim(substr($tmp, $info['header_size'])); //直接从header之后开始截取,因为 1.body可能为空 2.下载可能不全
  69. //$info['download_content_length'] > 0 ? substr($tmp, -$info['download_content_length']) : '';
  70. }
  71. $errno = curl_errno($ch);
  72. if ($errno) {
  73. self::$err = array(
  74. 'errno' => $errno,
  75. 'error' => curl_error($ch),
  76. );
  77. }
  78. curl_close($ch);
  79. return $result;
  80. }
  81. public static function getError()
  82. {
  83. return self::$err;
  84. }
  85. }