PHP 采集图片函数

php函数

2009-12-25 15:55

<?

function getimg($url, $filepath) {  

    if ($url == '') {  
        return false;  
    }  
    $ext = strrchr($url, '.');  

    if ($ext != '.gif' && $ext != '.jpg') {  
        return false;  
    }  

    //判断路经是否存在  
    !is_dir($filepath)?mkdir($filepath):null;  

    //获得随机的图片名,并加上后辍名  
    $filetime = time();  
    $filename = date("YmdHis",$filetime).rand(100,999).'.'.substr($url,-3,3);  

    //读取图片  
    $img = fetch_urlpage_contents($url);  
    //指定打开的文件  
    $fp = @ fopen($filepath.'/'.$filename, 'a');  
    //写入图片到指定的文本  
    fwrite($fp, $img);  
    fclose($fp);  
    return '/'.$filepath.'/'.$filename;  
}

function fetch_urlpage_contents($url){  
    $ch = curl_init();  
    curl_setopt ($ch, CURLOPT_URL, $url);  
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt ($ch, CURLOPT_TIMEOUT, 1000);  
    $file_contents = curl_exec($ch);  
    curl_close($ch);  
    return $file_contents;  
}

echo getimg(")   //图片地址 //保存路径 //返回保存后路径


?>