您的位置:首页 > 编程语言 > PHP开发

php获取远程文件内容与大小的函数代码

2013-07-13 11:10 861 查看
1,PHP 获取远程文件内容的代码:

<?
/**
获取远程文件内容
@param $url 文件http地址
*/
function fopen_url($url)
{
if (function_exists('file_get_contents')) {
$file_content = @file_get_contents($url);
} elseif (ini_get('allow_url_fopen') && ($file = @fopen($url, 'rb'))){
$i = 0;
while (!feof($file) && $i++ < 1000) {
$file_content .= strtolower(fread($file, 4096));
}
fclose($file);
} elseif (function_exists('curl_init')) {
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Trackback Spam Check'); //引用垃圾邮件检查
$file_content = curl_exec($curl_handle);
curl_close($curl_handle);
} else {
$file_content = '';
}
return $file_content;
}
?>


2,获取远程文件大小的php函数

<?php
/**
* 获取远程文件大小
* edit by www.jbxue.com
*/
function getFileSize($url){
$url = parse_url($url);
if($fp = @fsockopen($url['host'],empty($url['port'])?80:$url['port'],$error)){
fputs($fp,"GET ".(empty($url['path'])?'/':$url['path'])." HTTP/1.1\r\n");
fputs($fp,"Host:$url[host]\r\n\r\n");
while(!feof($fp)){
$tmp = fgets($fp);
if(trim($tmp) == ''){
break;
}else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
return trim($arr[1]);
}
}
return null;
}else{
return null;
}
}
//调用方法
echo getFileSize("http://www.jbxue.com/images/logo.gif")
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: