PHP远程下载文件到本地的函数

PHP 1461 0 2012-08-27

PHP远程下载文件到本地的函数
<?php
echo httpcopy("http://www.baidu.com/img/baidu_sylogo1.gif");

function httpcopy($url, $file="", $timeout=60) {
    $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
            return $file;
        } else {
            return false;
        }
    } else {
        $opts = array(
            "http"=>array(
            "method"=>"GET",
            "header"=>"",
            "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            //$http_response_header
            return $file;
        } else {
            return false;
        }
    }
}
?>

上一篇:PHP文件上传报错代码详解

下一篇:PHP get_headers()函数详解

讨论数量:1

天涯网魂 3 杠 5 星2012-08-27 10:39:16

补充说明:
经常写采集器发布接口需要使用到远程附件的功能,所以自己写了一个PHP远程下载文件到本地的函数,一般情况下已经够用了,如果服务器支持CURL函数, 程序则会优先选择CURL,因为测试结果表明CURL的响应时间及资源占用率比file_get_contents小得多;如果大家有好的建议及改进方 案,欢迎留言给我哦!

请先登录再发表讨论。 2024-04-28

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链