Rumah  >  Artikel  >  pembangunan bahagian belakang  >  一个读取远程文件的PHP函数

一个读取远程文件的PHP函数

WBOY
WBOYasal
2016-07-25 08:43:531006semak imbas

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

  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.0\r\n";
  9. $out .= "Accept: */*\r\n";
  10. $out .= "Accept-Language: zh-cn\r\n";
  11. $boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "\n")));
  12. $out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
  13. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  14. $out .= "Host: $host\r\n";
  15. $out .= 'Content-Length: '.strlen($post)."\r\n";
  16. $out .= "Connection: Close\r\n";
  17. $out .= "Cache-Control: no-cache\r\n";
  18. $out .= "Cookie: $cookie\r\n\r\n";
  19. $out .= $post;
  20. } else {
  21. $out = "GET $path HTTP/1.0\r\n";
  22. $out .= "Accept: */*\r\n";
  23. $out .= "Accept-Language: zh-cn\r\n";
  24. $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
  25. $out .= "Host: $host\r\n";
  26. $out .= "Referer: \r\n";
  27. $out .= "Connection: Close\r\n";
  28. $out .= "Cookie: $cookie\r\n\r\n";
  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 == "\r\n" || $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 }
  51. }
  52. }
  53. @fclose($fp);
  54. return $return;
  55. }
  56. }
复制代码

PHP


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn