2015-12-03 3 views
2

Я отправил свой код несколько дней назад, и сейчас я нахожусь в этом месте. Тем не менее, я приобрел случайные файлы, когда они zip становится zip.cpgz-файлом после распаковки. Я уверен, что это имеет какое-то отношение к тому, как я использовал массив в моем цикле, но я не совсем уверен, как это исправить.Загрузите случайные файлы как zip

<?php 
//./uploads 
$dir = "./uploads"; 
$nfiles = glob($dir.'*.{aiff}', GLOB_BRACE);  
$n=1; 
while ($n<=10){ 
$n ++; 
$arr[$n] = rand(2, sizeof($nfiles)-1); 
print($arr[$n]); 
print(" "); 
} 


$zip = new ZipArchive(); 
$zip_name = "zipfile.zip"; 
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ 
    $error .= "* Sorry ZIP creation failed at this time"; 
} 

foreach($arr as $file){ 
    $path = "./uploads".$file; 
    $zip->addFromString(basename($path), file_get_contents($path)); 
} 

$zip->close(); 

header('Content-Type: application/zip'); 
header('Content-disposition: attachment; filename='.$zip_name); 
readfile('zipfile.zip'); 

?> 

Кроме того, если вы любопытное потерял здесь my website я пытаюсь реализовать его. (нажмите кнопку загрузки)

+0

Когда я попробовал ссылку для скачивания, я получил архив zip с 21 пустым файлом! – RamRaider

+0

Кстати - html на вашем сайте недействителен - нет закрывающего тега 'a' для ссылки' upload', '

Следуйте за мной !, а затем паразитная дополнительная пара тегов body внизу ... – RamRaider

ответ

1

Недавно помогли другому пользователю получить что-то похожее на работу (без случайного выбора), и вы можете найти следующее полезное. Это выполняет поиск в каталоге для определенного расширения файла, а затем случайным образом выбирает 10 файлов, которые могут быть заархивированы и отправлены. Измените $sourcedir и $ext в надежде - это поможет.

/* From David Walsh's site - modified */ 
function create_zip($files = array(), $destination = '', $overwrite = false) { 
    if(file_exists($destination) && !$overwrite) { return false; } 
    $valid_files = array(); 
    if(is_array($files)) { 
     foreach($files as $file) if(file_exists($file)) $valid_files[] = $file; 
    } 
    if(count($valid_files)) { 
     $zip = new ZipArchive(); 
     if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) return false; 
     foreach($valid_files as $file) $zip->addFile($file, pathinfo($file, PATHINFO_FILENAME)); 
     $zip->close(); 
     return file_exists($destination); 
    } 
    return false; 
} 
/* Simple function to send a file */ 
function sendfile($filename=NULL, $filepath=NULL){ 
    if(file_exists($filepath)){ 

     if(!is_file($filepath) or connection_status()!=0) return FALSE; 

     header("Cache-Control: no-store, no-cache, must-revalidate"); 
     header("Pragma: no-cache"); 
     header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT"); 
     header("Content-Type: application/octet-stream"); 
     header("Content-Length: ".(string)(filesize($filepath))); 
     header("Content-Disposition: inline; filename={$filename}"); 
     header("Content-Transfer-Encoding: binary\n"); 

     if($file = @fopen($filepath, 'rb')) { 
      while([email protected]($file) and (connection_status()==0)) { 
       print(fread($file, 1024*8)); 
       flush(); 
      } 
      @fclose($file); 
     } 
     return((connection_status()==0) and !connection_aborted()); 
    } 
} 



/* Select a random entry from the array */ 
function pick($arr){ 
    return $arr[ rand(0, count($arr)-1) ]; 
} 

/* The directory to which the zip file will be written before sending */ 
$target=__DIR__.'\zipfile.zip'; 

/* The directory you wish to scan for files or create an array in some other manner */ 
$sourcedir = 'C:\Temp\temp_uploads'; 

/* File extension to scan for */ 
$ext='txt'; 

/* Placeholder to store files*/ 
$output=array(); 

/* Scan the dir, or as mentioned, create an array of files some other way */ 
$files=glob(realpath($sourcedir) . DIRECTORY_SEPARATOR . '*.'.$ext); 


/* Pick 10 random files from all possible files */ 
do{ 
    $rnd=pick($files); 
    $output[ $rnd ] = $rnd; 
}while(count($output) < 10); 

/* streamline array */ 
$output=array_values($output); 



if($target) { 
    /* Zip the contents */ 
    $result=create_zip($output, $target, true); 

    /* Send the file - zipped! */ 
    if($result) { 
     $res=call_user_func('sendfile', 'zipfile.zip', $target); 
     if($res) unlink($target); 
    } 
} 
+0

ты мужчина! вау, это делает гораздо больше смысла делать, по-видимому, мой компьютер - единственный, который не позволяет мне распаковать ... он работает на вас? –

+0

Я мог бы скачать zip-файл, но все 21 файл был пустым, и теперь я получаю «Неустранимая ошибка: максимальное время выполнения 30 секунд превышено в /home/ghostx19/public_html/phDownloader.php в строке 47' – RamRaider

+0

как я должен исправить эта ошибка..и извиниться, я все еще лежу –

1

Вы уверены, что он не работает? Я загрузил ваш zip-файл и извлек его, и у меня появились файлы UploadsX. Поэтому я не получаю файл zip.cpgz.

+0

woah sweet! VVV –

Смежные вопросы