Http.class.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. namespace Util;
  3. /**
  4. * Http 工具类
  5. * 提供一系列的Http方法
  6. */
  7. class Http
  8. {
  9. /**
  10. * 采集远程文件
  11. * @access public
  12. * @param string $remote 远程文件名
  13. * @param string $local 本地保存文件名
  14. * @return mixed
  15. */
  16. public static function curlDownload($remote, $local)
  17. {
  18. $cp = curl_init($remote);
  19. $fp = fopen($local, "w");
  20. curl_setopt($cp, CURLOPT_FILE, $fp);
  21. curl_setopt($cp, CURLOPT_HEADER, 0);
  22. curl_exec($cp);
  23. curl_close($cp);
  24. fclose($fp);
  25. }
  26. /**
  27. * 使用 fsockopen 通过 HTTP 协议直接访问(采集)远程文件
  28. * 如果主机或服务器没有开启 CURL 扩展可考虑使用
  29. * fsockopen 比 CURL 稍慢,但性能稳定
  30. * @static
  31. * @access public
  32. * @param string $url 远程URL
  33. * @param array $conf 其他配置信息
  34. * int limit 分段读取字符个数
  35. * string post post的内容,字符串或数组,key=value&形式
  36. * string cookie 携带cookie访问,该参数是cookie内容
  37. * string ip 如果该参数传入,$url将不被使用,ip访问优先
  38. * int timeout 采集超时时间
  39. * bool block 是否阻塞访问,默认为true
  40. * @return mixed
  41. */
  42. public static function fsockopenDownload($url, $conf = array())
  43. {
  44. $return = '';
  45. if (!is_array($conf)) {
  46. return $return;
  47. }
  48. $matches = parse_url($url);
  49. !isset($matches['host']) && $matches['host'] = '';
  50. !isset($matches['path']) && $matches['path'] = '';
  51. !isset($matches['query']) && $matches['query'] = '';
  52. !isset($matches['port']) && $matches['port'] = '';
  53. $host = $matches['host'];
  54. $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
  55. $port = !empty($matches['port']) ? $matches['port'] : 80;
  56. $conf_arr = array(
  57. 'limit' => 0,
  58. 'post' => '',
  59. 'cookie' => '',
  60. 'ip' => '',
  61. 'timeout' => 15,
  62. 'block' => true,
  63. );
  64. foreach (array_merge($conf_arr, $conf) as $k => $v) {
  65. ${$k} = $v;
  66. }
  67. if ($post) {
  68. if (is_array($post)) {
  69. $post = http_build_query($post);
  70. }
  71. $out = "POST $path HTTP/1.0\r\n";
  72. $out .= "Accept: */*\r\n";
  73. //$out .= "Referer: $boardurl\r\n";
  74. $out .= "Accept-Language: zh-cn\r\n";
  75. $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
  76. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  77. $out .= "Host: $host\r\n";
  78. $out .= 'Content-Length: ' . strlen($post) . "\r\n";
  79. $out .= "Connection: Close\r\n";
  80. $out .= "Cache-Control: no-cache\r\n";
  81. $out .= "Cookie: $cookie\r\n\r\n";
  82. $out .= $post;
  83. } else {
  84. $out = "GET $path HTTP/1.0\r\n";
  85. $out .= "Accept: */*\r\n";
  86. //$out .= "Referer: $boardurl\r\n";
  87. $out .= "Accept-Language: zh-cn\r\n";
  88. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  89. $out .= "Host: $host\r\n";
  90. $out .= "Connection: Close\r\n";
  91. $out .= "Cookie: $cookie\r\n\r\n";
  92. }
  93. $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
  94. if (!$fp) {
  95. return '';
  96. } else {
  97. stream_set_blocking($fp, $block);
  98. stream_set_timeout($fp, $timeout);
  99. @fwrite($fp, $out);
  100. $status = stream_get_meta_data($fp);
  101. if (!$status['timed_out']) {
  102. while (!feof($fp)) {
  103. if (($header = @fgets($fp)) && ("\r\n" == $header || "\n" == $header)) {
  104. break;
  105. }
  106. }
  107. $stop = false;
  108. while (!feof($fp) && !$stop) {
  109. $data = fread($fp, (0 == $limit || $limit > 8192 ? 8192 : $limit));
  110. $return .= $data;
  111. if ($limit) {
  112. $limit -= strlen($data);
  113. $stop = $limit <= 0;
  114. }
  115. }
  116. }
  117. @fclose($fp);
  118. return $return;
  119. }
  120. }
  121. /**
  122. * 下载文件
  123. * 可以指定下载显示的文件名,并自动发送相应的Header信息
  124. * 如果指定了content参数,则下载该参数的内容
  125. * @static
  126. * @access public
  127. * @param string $filename 下载文件名
  128. * @param string $showname 下载显示的文件名
  129. * @param string $content 下载的内容
  130. * @param integer $expire 下载内容浏览器缓存时间
  131. * @return void
  132. */
  133. public static function download($filename, $showname = '', $content = '', $expire = 180)
  134. {
  135. if (is_file($filename)) {
  136. $length = filesize($filename);
  137. } elseif (is_file(UPLOAD_PATH . $filename)) {
  138. $filename = UPLOAD_PATH . $filename;
  139. $length = filesize($filename);
  140. } elseif ('' != $content) {
  141. $length = strlen($content);
  142. } else {
  143. E($filename . L('下载文件不存在!'));
  144. }
  145. if (empty($showname)) {
  146. $showname = $filename;
  147. }
  148. $showname = self::get_basename($showname);
  149. if (!empty($filename)) {
  150. $finfo = new \finfo(FILEINFO_MIME);
  151. $type = $finfo->file($filename);
  152. } else {
  153. $type = "application/octet-stream";
  154. }
  155. //发送Http Header信息 开始下载
  156. header("Pragma: public");
  157. header("Cache-control: max-age=" . $expire);
  158. //header('Cache-Control: no-store, no-cache, must-revalidate');
  159. header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expire) . "GMT");
  160. header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . "GMT");
  161. header("Content-Disposition: attachment; filename=" . $showname);
  162. header("Content-Length: " . $length);
  163. header("Content-type: " . $type);
  164. header('Content-Encoding: none');
  165. header("Content-Transfer-Encoding: binary");
  166. if ('' == $content) {
  167. readfile($filename);
  168. } else {
  169. echo ($content);
  170. }
  171. exit();
  172. }
  173. /**
  174. * 获取文件的名称,兼容中文名
  175. * @return string
  176. */
  177. public static function get_basename($filename)
  178. {
  179. return preg_replace('/^.+[\\\\\\/]/', '', $filename);
  180. }
  181. /**
  182. * 显示HTTP Header 信息
  183. * @return string
  184. */
  185. public static function getHeaderInfo($header = '', $echo = true)
  186. {
  187. ob_start();
  188. $headers = getallheaders();
  189. if (!empty($header)) {
  190. $info = $headers[$header];
  191. echo ($header . ':' . $info . "\n");
  192. } else {
  193. foreach ($headers as $key => $val) {
  194. echo ("$key:$val\n");
  195. }
  196. }
  197. $output = ob_get_clean();
  198. if ($echo) {
  199. echo (nl2br($output));
  200. } else {
  201. return $output;
  202. }
  203. }
  204. /**
  205. * HTTP Protocol defined status codes
  206. * @param int $num
  207. */
  208. public static function sendHttpStatus($code)
  209. {
  210. static $_status = array(
  211. // Informational 1xx
  212. 100 => 'Continue',
  213. 101 => 'Switching Protocols',
  214. // Success 2xx
  215. 200 => 'OK',
  216. 201 => 'Created',
  217. 202 => 'Accepted',
  218. 203 => 'Non-Authoritative Information',
  219. 204 => 'No Content',
  220. 205 => 'Reset Content',
  221. 206 => 'Partial Content',
  222. // Redirection 3xx
  223. 300 => 'Multiple Choices',
  224. 301 => 'Moved Permanently',
  225. 302 => 'Found', // 1.1
  226. 303 => 'See Other',
  227. 304 => 'Not Modified',
  228. 305 => 'Use Proxy',
  229. // 306 is deprecated but reserved
  230. 307 => 'Temporary Redirect',
  231. // Client Error 4xx
  232. 400 => 'Bad Request',
  233. 401 => 'Unauthorized',
  234. 402 => 'Payment Required',
  235. 403 => 'Forbidden',
  236. 404 => 'Not Found',
  237. 405 => 'Method Not Allowed',
  238. 406 => 'Not Acceptable',
  239. 407 => 'Proxy Authentication Required',
  240. 408 => 'Request Timeout',
  241. 409 => 'Conflict',
  242. 410 => 'Gone',
  243. 411 => 'Length Required',
  244. 412 => 'Precondition Failed',
  245. 413 => 'Request Entity Too Large',
  246. 414 => 'Request-URI Too Long',
  247. 415 => 'Unsupported Media Type',
  248. 416 => 'Requested Range Not Satisfiable',
  249. 417 => 'Expectation Failed',
  250. // Server Error 5xx
  251. 500 => 'Internal Server Error',
  252. 501 => 'Not Implemented',
  253. 502 => 'Bad Gateway',
  254. 503 => 'Service Unavailable',
  255. 504 => 'Gateway Timeout',
  256. 505 => 'HTTP Version Not Supported',
  257. 509 => 'Bandwidth Limit Exceeded',
  258. );
  259. if (isset($_status[$code])) {
  260. header('HTTP/1.1 ' . $code . ' ' . $_status[$code]);
  261. }
  262. }
  263. }