现在的位置: 首页 > 综合 > 正文

获取 远程文件 下载

2012年05月24日 ⁄ 综合 ⁄ 共 2457字 ⁄ 字号 评论关闭

<?php
//计算远程文件大小
function remote_filesize($url,$user='',$pw='')
{
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if (!empty($user)&&!empty($pw)) {
$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$okay = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $head, $matches);
if (isset($matches[1])) {
$size = $matches[1];
} else {
$size = 'unknown';
}
return $size;
}
function get_file($url, $folder = "./") {   
    set_time_limit (24 * 60 * 60); // 设置超时时间   
    $destination_folder = $folder . 'faguicn/'; // 文件下载保存目录,默认为当前文件目录   
    if (!is_dir($destination_folder)) { // 判断目录是否存在   
            mkdirs($destination_folder); // 如果没有就建立目录   
    }    
    $newfname = $destination_folder . basename($url); // 取得文件的名称   
    $file = fopen ($url, "rb"); // 远程下载文件,二进制模式   
    if ($file) { // 如果下载成功   
            $newf = fopen ($newfname, "wb"); // 远在文件文件   
        if ($newf) // 如果文件保存成功   
            while (!feof($file)) { // 判断附件写入是否完整   
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8); // 没有写完就继续   
        }    
    }    
    if ($file) {   
        fclose($file); // 关闭远程文件   
    }    
    if ($newf) {   
        fclose($newf); // 关闭本地文件   
    }    
    return true;   
}    
  
function mkdirs($path , $mode = "0755") {   
    if (!is_dir($path)) { // 判断目录是否存在   
            mkdirs(dirname($path), $mode); // 循环建立目录     
        mkdir($path, $mode); // 建立目录   
    }    
    return true;   
}    
// 使用示例   
//连接数据库
$user="root";
$host="localhost";
$password="root"; 
$dbname="test"; //所查询的库表名;
//连接MySQL数据库
mysql_connect("$host","$user","$password");
$db = mysql_select_db("$dbname") or die("无法连接数据库!");
$sql = "SELECT * from table WHERE 1";//生成查询记录数的SQL语句
$rst = mysql_query($sql) or die("无法执行SQL语句:$sql !"); //查询记录数
while($row=mysql_fetch_array($rst)){
  if($row['cn_url']!=""){
      $url = "http://file.foodvip.net/".$row['cn_url'];
 //echo $url."<br/>";
//检查远程文件是否存在。
/*
$file_up=$row['cn_url'];
    if(file_exists($file_up)){
        //echo "<font color='red'>文件已经存在!!",'</font><br />';
      }else{
 echo $row['title'].'    '.$row['cn_url']."该文件不存在!!",'<br />';
    }*/
if(get_file($url)){
echo '1','<br/>';
}else{
echo '失败',$row['title'];
}
/*$i2 = "CCFFV/".$row['bzname'].".pdf";
$i1= $row['cn_url'];
$ii =rename($i1,$i2);
if($ii){
echo "修改成功";
}else{
echo "修改失败";
}*/

  }
  //echo get_file("http://huishi.foodmate.net/biaofa/lawuploads/".$row['cn_url']."");  
}
/*
//$url = "http://ceshi.com/2072027.pdf";

$filesize = remote_filesize($url,$user='',$pw='');

//显示远程文件大小
$ii = substr($filesize,0,5)."kB";
 if($ii=="169kB"){
 echo get_file('http://ceshi.com/29084546.pdf');  
 }
*/
 //判断文件是否存在
 
?>   

抱歉!评论已关闭.