vendredi 4 décembre 2015

How can I remove duplicates and add a new unique file?

I have on my website to grab 5 random files from all the files in my directory and all is going well but about %50 of the time I get a duplicate. I would like to: 1) Remove duplicate 2) Replace with new unique file

.. or maybe I can prevent duplicates in an easier manner all together? I tried to find a function for this without asking a question of here but I have not found one. Any ideas? Thanks!!

 <?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');
}

?>




Aucun commentaire:

Enregistrer un commentaire