zoukankan      html  css  js  c++  java
  • PHP代码实现远程下载文件到本地的函数

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

    <?php

    /*

    pathinfo -- 返回文件路径的信息
    array pathinfo ( string path [, int options] )
    pathinfo() 返回一个关联数组包含有 path 的信息。包括以下的数组单元:dirname,basename 和 extension。 
    可以通过参数 options 指定要返回哪些单元。它们包括:PATHINFO_DIRNAME,PATHINFO_BASENAME 和 PATHINFO_EXTENSION。默认是返回全部的单元。 
    例子 1. pathinfo() 例子
    <?php
    $path_parts = pathinfo("/www/htdocs/index.html");
    echo $path_parts["dirname"] . "\n";
    echo $path_parts["basename"] . "\n";
    echo $path_parts["extension"] . "\n";
    ?> 
    上例将输出:
    /www/htdocs
    index.html
    html
     
    定义和用法

    mkdir() 函数创建目录。

    若成功,则返回 true,否则返回 false。

    语法
    mkdir(path,mode,recursive,context)
    参数描述
    path必需。规定要创建的目录的名称。
    mode必需。规定权限。默认是 0777。
    recursive必需。规定是否设置递归模式。
    context必需。规定文件句柄的环境。
    Context 是可修改流的行为的一套选项。
    说明

    mkdir() 尝试新建一个由 path指定的目录。

    默认的 mode是 0777,意味着最大可能的访问权。

    */
    echo httpcopy("http://www.baidu.com/img/baidu_sylogo1.gif");

    function httpcopy($url, $file="", $timeout=60) {

        //如果文件名为空,使用pathinfo()方法返回文件名
        $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;

       //取得文件路径
        $dir = pathinfo($file,PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir,0777,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;
            }
        }
    }
    ?>

  • 相关阅读:
    【Android】Android连接SQLite3数据库的操作
    【exe4j】如何利用exe4j把java桌面程序生成exe文件
    Http网络协议
    【Spring】spring的7个模块
    【jsp】JSP中page指令isThreadSafe
    【MySQL】乐观锁和悲观锁
    【Eclipse】Eclipse上如何集成SVN插件
    【MySQL】mysql出现错误“ Every derived table must have its own alias”
    【Struts2】SSH如何返回JSON数据
    【Oracle】Oracle 的过程化SQL(PLSQL)中NULL值的处理
  • 原文地址:https://www.cnblogs.com/akatuki/p/4246812.html
Copyright © 2011-2022 走看看