【发布时间】:2015-12-04 21:43:37
【问题描述】:
我在我的网站上从目录中的所有文件中抓取 5 个随机文件,一切顺利,但大约 %50 的时间我得到了副本。我想: 1)删除重复 2) 替换为新的唯一文件
.. 或者我可以以更简单的方式一起防止重复?我试图在不问这里的问题的情况下为此找到一个功能,但我还没有找到。有任何想法吗?谢谢!!
<?php
//define stuff
$dir = "uploads/";
$allfiles = array_diff(scandir($dir), array('.', '..'));
echo '<pre>';
print_r("all files ready for access");
echo '<pre>';
// create zip
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
else {
echo '<pre>';
print("created zip");
echo '<pre>';
}
// array of random files
$n=1;
while ($n<=6){
$n ++;
$file = array_rand($allfiles);
$randomfile = $allfiles[$file];
echo '<pre>';
print_r($randomfile);
echo '<pre>';
if (file_exists($dir.$randomfile)) {
$content = $dir.$randomfile;
echo '<pre>';
print_r($content);
echo '<pre>';
$zip->addfile($content,$randomfile);
echo 'ok';
} else {
echo 'failed';
}
}
//present for download
$zip->close();
ob_get_clean();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zip_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_name));
readfile($zip_name);
if(file_exists($zip_name))
{
unlink('zipfile.zip');
}
?>
【问题讨论】:
-
您可以创建一个包含所有文件条目的数组,然后使用
shuffle()随机化该数组,然后选择该数组中的前 5 个项目。
标签: php file random download unique