概述
转自:http://www.qiandabao.com/wdgz/47.html
使用PHP读取远程文件的四种方法
1 fopen()
2 file_get_contents()
3 curl
4 socket
fopen()和file_get_contents()需要在php.ini配置文件中设置allow_url_open = on
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;)');
$contents = curl_exec($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;
}
$timout = 10;
$response = '';
$fp = @fsockopen($host, $port, $errno, $errstr, $timout);
if (!$fp) {
echo "Connect to $url failed";
} else {
fputs($fp, "Get $path HTTP/1.0rn".
"Host: $hostrn".
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1;) rn".
"Accept:*/*rn".
"Accept-Language: zh-CN, zh;q=0.5rn".
"Accept-Charset: GB-2312, utf-8;q=0.7,*'q=0.7rn".
"Keep_Alive: 300rn".
"Connection: keep-alivern".
"Referer: http://$urlrnrn");
while ($line = fread($fp, 4096)) {
$response .= $line;
}
fclose($fp);
$pos = strpos($response, "rnrn");
$response = substr($response, $pos +4);
}
return $response;
}
最后
以上就是诚心鼠标为你收集整理的使用PHP读取远程文件的四种方法的全部内容,希望文章能够帮你解决使用PHP读取远程文件的四种方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复