在昨天做連接埠測試的基礎上研究一下PHP上傳與下載的代碼,結果想起前段時間筆試題有一道題是在上傳檔案時顯示檔案內容,讓我對PHP實現讀取遠程檔案的功能高度興趣,以下是代碼:
| 01 |
function urlfopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE , $ip = '', $timeout = 15, $block = TRUE, $encodetype = 'URLENCODE') { |
| 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; |
| 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"; |
| 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"; |
| 31 |
$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr,$timeout); |
| 35 |
stream_set_blocking($fp, $block); |
| 36 |
stream_set_timeout($fp, $timeout); |
| 38 |
$status = stream_get_meta_data($fp); |
| 39 |
if(!$status['timed_out']) { |
| 41 |
if(($header = @fgets($fp)) && ($header == "\r\n" $header =="\n")) { |
| 47 |
while(!feof($fp) && !$stop) { |
| 48 |
$data = fread($fp, ($limit == 0 $limit > 8192 ? 8192 :$limit)); |
| 51 |
$limit -= strlen($data); |