欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP实现读取远程文件功能

程序员文章站 2022-03-09 09:25:42
...
在昨天做端口测试的基础上研究一下PHP上传与下载的代码,结果想起前段时间笔试题有一道题是在上传文件时显示文件内容,让我对PHP实现读取远程文件的功能很感兴趣,以下是代码:
01 function urlfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE , $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') {

02 $return = '';

03 $matches = parse_url($url);

04 $host = $matches['host'];

05 $path = $matches['path'] ? $matches['path'].(isset($matches['query']) ? '?'.$matches['query'] : '') : '/';

06 $port = !empty($matches['port']) ? $matches['port'] : 80;

07

08 if($post) {

09 $out = "POST $path HTTP/1.0\r\n";

10 $out .= "Accept: */*\r\n";

11 $out .= "Accept-Language: zh-cn\r\n";

12 $boundary = $encodetype == 'URLENCODE' ? '' : ';'.substr($post, 0, trim(strpos($post, "\n")));

13 $out .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";

14 $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";

15 $out .= "Host: $host\r\n";

16 $out .= 'Content-Length: '.strlen($post)."\r\n";

17 $out .= "Connection: Close\r\n";

18 $out .= "Cache-Control: no-cache\r\n";

19 $out .= "Cookie: $cookie\r\n\r\n";

20 $out .= $post;

21 } else {

22 $out = "GET $path HTTP/1.0\r\n";

23 $out .= "Accept: */*\r\n";

24 $out .= "Accept-Language: zh-cn\r\n";

25 $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";

26 $out .= "Host: $host\r\n";

27 $out .= "Referer: \r\n";

28 $out .= "Connection: Close\r\n";

29 $out .= "Cookie: $cookie\r\n\r\n";

30 }

31 $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr,$timeout);

32 if(!$fp) {

33 return '';

34 } else {

35 stream_set_blocking($fp, $block);

36 stream_set_timeout($fp, $timeout);

37 @fwrite($fp, $out);

38 $status = stream_get_meta_data($fp);

39 if(!$status['timed_out']) {

40 while (!feof($fp)) {

41 if(($header = @fgets($fp)) && ($header == "\r\n" $header =="\n")) {

42 break;

43 }

44 }

45

46 $stop = false;

47 while(!feof($fp) && !$stop) {

48 $data = fread($fp, ($limit == 0 $limit > 8192 ? 8192 :$limit));

49 $return .= $data;

50 if($limit) {

51 $limit -= strlen($data);

52 $stop = $limit

53 }

54 }

55 }

56 @fclose($fp);

57 return $return;

58 }

59 }