Home >Backend Development >PHP Tutorial >A PHP function that reads remote files

A PHP function that reads remote files

WBOY
WBOYOriginal
2016-07-25 08:43:531065browse

一个读取远程文件的函数,非常好用!

  1. function urlfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE , $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') {
  2. $return = '';
  3. $matches = parse_url($url);
  4. $host = $matches['host'];
  5. $path = $matches['path'] ? $matches['path'].(isset($matches['query']) ? '?'.$matches['query'] : '') : '/';
  6. $port = !empty($matches['port']) ? $matches['port'] : 80;
  7. if($post) {
  8. $out = "POST $path HTTP/1.0rn";
  9. $out .= "Accept: */*rn";
  10. $out .= "Accept-Language: zh-cnrn";
  11. $boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "n")));
  12. $out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencodedrn" : "Content-Type: multipart/form-data$boundaryrn";
  13. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]rn";
  14. $out .= "Host: $hostrn";
  15. $out .= 'Content-Length: '.strlen($post)."rn";
  16. $out .= "Connection: Closern";
  17. $out .= "Cache-Control: no-cachern";
  18. $out .= "Cookie: $cookiernrn";
  19. $out .= $post;
  20. } else {
  21. $out = "GET $path HTTP/1.0rn";
  22. $out .= "Accept: */*rn";
  23. $out .= "Accept-Language: zh-cnrn";
  24. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]rn";
  25. $out .= "Host: $hostrn";
  26. $out .= "Referer: rn";
  27. $out .= "Connection: Closern";
  28. $out .= "Cookie: $cookiernrn";
  29. }
  30. $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
  31. if(!$fp) {
  32. return '';
  33. } else {
  34. stream_set_blocking($fp, $block);
  35. stream_set_timeout($fp, $timeout);
  36. @fwrite($fp, $out);
  37. $status = stream_get_meta_data($fp);
  38. if(!$status['timed_out']) {
  39. while (!feof($fp)) {
  40. if(($header = @fgets($fp)) && ($header == "rn" || $header == "n")) {
  41. break;
  42. }
  43. }
  44. $stop = false;
  45. while(!feof($fp) && !$stop) {
  46. $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
  47. $return .= $data;
  48. if($limit) {
  49. $limit -= strlen($data);
  50. $stop = $limit <= 0;
  51. }
  52. }
  53. }
  54. @fclose($fp);
  55. return $return;
  56. }
  57. }
复制代码

PHP


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn