2012-09-21 71 views
2

我正在構建基於codeigniter的應用程序。在這裏,我只需要下載具有.zip擴展名並上傳到本地驅動器的文件。但要做到這一點,我已給定一個名爲get_zip內容功能如下:如何僅存儲從其他網站下載的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文件將被下載並上傳到我的本地驅動器。

+0

你可以得到的擴展名在文件名末尾,並檢查它是否是.zip或不是。你有沒有嘗試過任何東西? – scrappedcola

+0

其實我沒怎麼檢查 – user1684080

+0

對於這個我建議使用[DirectoryIterator](http://php.net/manual/en/class.directoryiterator.php)或PHP 5.3> = [FilesystemIterator](http ://php.net/manual/en/class.filesystemiterator.php) – dbf

回答

1

由於文件名只是一個字符串,你可以使用/從這個SO question修改答案:

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

編輯:

對於錯誤代碼嘗試:

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

謝謝,但我怎麼能確保它的文件我的意思是,如果該網站的地址是錯誤的,那麼它顯示一個錯誤頁面,該文件正在上傳例如,返回http://stackoverflow.com/test.zip這些文件不屬於它只是上傳頁面未找到文件 – user1684080

+0

您可以檢查curl調用的狀態,並查看調用的狀態。 http://php.net/manual/en/book.curl.php。在評論中查看評論弗蘭克在交流.com 2011年3月11日01:29。 – scrappedcola

相關問題