站长论坛

标题: 使用PHP读取远程文件 [打印本页]

作者: superadmin    时间: 2008-5-8 09:13
标题: 使用PHP读取远程文件
使用php读取远程文件有4种方式:

fopen()
file_get_contents()
curl函数
socket函数
fopen()与file_get_contents()需要在php.ini配置文件中激活allow_url_fopen选项。

fopen()方式

$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
file_get_contents()方式

$contents = file_get_contents('http://www.example.com/');
curl函数

if (function_exists('curl_init')){
   $ch=curl_init();
   curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; )');
   $content=curl_ex ec($ch);
   curl_close($ch);
}
socket方式

function getRemoteFile($url)
{
   $parsedUrl = parse_url($url);
   $host = $parsedUrl['host'];
   if (isset($parsedUrl['path'])) {
      $path = $parsedUrl['path'];
   } else {
      $path = '/';
   }
  
   if (isset($parsedUrl['query'])) {
      $path .= '?' . $parsedUrl['query'];
   }
  
   if (isset($parsedUrl['port'])) {
      $port = $parsedUrl['port'];
   } else {
      $port = '80';
   }
  
   $timeout = 10;
   $response = '';
   $fp = @fsockopen($host, '80', $errno, $errstr, $timeout );
   if( !$fp ) {
      echo "连接$url失败";
   } else {
      fputs($fp, "GET $path HTTP/1.0\r\n" .
                 "Host: $host\r\n" .
                 "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1;) \r\n" .
                 "Accept: */*\r\n" .
                 "Accept-Language: zh-CN,zh;q=0.5\r\n" .
                 "Accept-Charset: GB-2312,utf-8;q=0.7,*;q=0.7\r\n" .
                 "Keep-Alive: 300\r\n" .
                 "Connection: keep-alive\r\n" .
                 "Referer: http://$host\r\n\r\n");
  
      while ( $line = fread( $fp, 4096 ) ) {
         $response .= $line;
      }
  
      fclose( $fp );
      $pos      = strpos($response, "\r\n\r\n");
      $response = substr($response, $pos + 4);
   }
  
   return $response;
}




欢迎光临 站长论坛 (http://tzlink.com/bbs/) Powered by Discuz! X3.2