Home > php教程 > php手册 > 一个获取远端文件的函数(Linux和Windows均适用)

一个获取远端文件的函数(Linux和Windows均适用)

WBOY
Release: 2016-06-21 09:12:15
Original
974 people have browsed it

window|函数

为了获取远端文件,编写了下面的一个小函数,基本各方面都考虑了,大家看看吧:
function getpic($url,$dir,$name){
    //获取url文件,然后存放到dir目录中,以name为文件名。
    //如果缺省文件名,则保留原文件名。
    $tmp=split("/",$url);
    $fname=$tmp[count($tmp)-1];//获取文件名
    if(empty($name)) {
        $name=$fname;//设定好文件名
    }else{//判断是否更改了文件的扩展名,如果更改的话,则改为文件本身的扩展名。
        $tmp1=split("\.",$fname);
        $tmp2=split("\.",$name);
        if(strcmp($tmp1[1],$tmp2[1])!=0) $name=$tmp2[0].".".$tmp1[1];
    }
    if(strstr($dir,"\\")){//说明是Windows环境下的目录
        if(substr($dir,-2)=="\\") $file=$dir.$name;else $file=$dir."\\".$name;
    }else{        
        if(substr($dir,"/")){//说明是Linux环境下的目录
            if(substr($dir,-1)=="/") $file=$dir.$name;else $file=$dir."/".$fname;
        }
        else{ //给了一个非法的目录,函数退出
            echo "error directory!";
            return ;
        }
    }
    if(!(file_exists("$dir") && is_dir("$dir"))) {//如果目录不存在,则创建目录
        mkdir($dir,0777);
    }
    if(file_exists($file)) return;//如果文件存在,则放弃操作
    $fpo=fopen($file,"wb");
    if(!$fpo){
        echo "Sorry,create file:$file failure!Check your right!";
        return ;
    }
    $num=0;
    do{
        $num++;
        $fpi=fopen($url,"r");
        if(!$fpi) echo "open remote file falure...Retry!\r\n";
    }while(!$fpi && $num    if(!fpi){
        echo "The network is buzy or Bad URL!";
        return ;
    }else echo "Open file OK!Now transfer....";
    while(!feof($fpi)){
        $cont=fread($fpi,128);
        fwrite($fpo,$cont,128);
    }
    fclose($fpi);
    fclose($fpo);
    echo "Success!";
}



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template