【问题标题】:How to store only zip files downloaded from other website如何仅存储从其他网站下载的 zip 文件
【发布时间】:2012-09-21 20:02:33
【问题描述】:

我正在构建一个基于 codeigniter 的应用程序。在这里,我只需要下载具有 .zip 扩展名的文件并上传到我的本地驱动器中。但为此我得到了一个名为 get_zip 的函数,内容如下:

<?php
function get_file($file, $localpath, $newfilename)
{
    $err_msg = '';
    $out = fopen($localpath.$newfilename,"wb");
    if ($out == FALSE){
        print "File not opened<br>";
        exit;
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FILE, $out);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $file);

    curl_exec($ch);
    if( curl_error($ch) )
    {
        echo "<br>Error is : ".curl_error ( $ch);
    }


    curl_close($ch);
    //fclose($ch);
    return $localpath.$newfilename;

}//end function


function directory_map_echo($source_dir, $directory_depth = 0, $hidden = FALSE)
{
    if ($fp = @opendir($source_dir))
    {
        $filedata   = '';
        $new_depth  = $directory_depth - 1;
        $source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;

        while (FALSE !== ($file = readdir($fp)))
        {
            // Remove '.', '..', and hidden files [optional]
            if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
            {
                continue;
            }

            if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file))
            {
                $filedata .= 'directory:'.$file.directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden);
            }
            else
            {
                $filedata .= $file;
            }
        }

        closedir($fp);
        return $filedata;
    }

    return FALSE;
}

但问题是我如何限制只下载 .zip 文件并将其上传到我的本地驱动器。

【问题讨论】:

  • 您可以从文件名末尾获取扩展名并检查它是否为 .zip...您尝试过什么吗?
  • 其实我没怎么查
  • 为此我建议使用 DirectoryIterator 或 PHP 5.3 >= FilesystemIterator

标签: php html codeigniter


【解决方案1】:

由于文件名只是一个字符串,您可以使用/修改来自此SO question 的答案:

$rex = "/^.*\.(zip)$/i";
preg_match($rex, $file)

编辑:

对于错误代码尝试:

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 if($httpCode == 404){ //do some error handling }

【讨论】:

  • 谢谢,但是我怎样才能确保它是一个文件,我的意思是如果站点的地址错误,那么它会显示一个错误页面并且正在上传该文件例如返回 stackoverflow.com/test.zip 文件没有属于它只是上传页面未找到文件
  • 你可以检查你的 curl 调用的状态,看看调用的状态是什么。 php.net/manual/en/book.curl.php。在 cmets 中查看 frank 在internetinet dot com 11-Mar-2011 01:29 的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2018-01-03
  • 2021-04-20
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多