[英]Download Random File From Directory
所以我有一個名為/ kv /的目錄,我想要它,所以當您轉到blah.com/getkv.php時,它將從該目錄下載一個隨機文件。 如果可能的話,我也希望它在下載文件后也將其刪除。 所有幫助將不勝感激!
您可以按數字順序存儲文件,然后通過生成隨機數來隨機選擇一個文件。
$random = mt_rand(1,100); //The amount of files you have
接下來,一旦選擇了文件,就可以設置下載標題
$file="/path/to/file/".$random.".png"; //file location
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
最后用刪除文件
delete($file);
選擇隨機文件的另一種方法是索引一個文件夾,然后隨機選擇其中一個文件。
進行檢查以確保文件存在也是明智的。
這是一些從目錄中獲取隨機文件的PHP:
$files = glob('*.{php,html}', GLOB_BRACE);
$file = $files[rand(0,count($files) - 1)];
然后添加viralpickaxe提供的部分答案:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
...並從目錄中刪除文件:
unlink($file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.