在目录中查找文件的最佳方法是什么 |.PHP



我需要使用 php 读取目录中的所有文件。所以我需要像这样返回

array(
        'content_type' => 'application/zip', 
        'suggested_name' => 'this_is_example.zip', 
        'protected_path' => 'download/this_is_example.zip'
    ),

我的生成文件是这样的:

$download_list = array();
    if(is_array($PROTECTED_DOWNLOADS)) {
        foreach ($PROTECTED_DOWNLOADS as $key => $download) {
            // Create a new key
            $new = uniqid('key',TRUE);
            // get download link and file size
            $download_link = "http://" . $_SERVER['HTTP_HOST'] . DOWNLOAD_PATH . "?key=" . $new . "&i=" . $key; 
            $filesize = human_filesize(filesize($download['protected_path']), 2);
            $filename = ($download['suggested_name']);
            // Add to the download list
            $download_list[] = array(
                'download_link' => $download_link,
                'filename' => $filename,
                'filesize' => $filesize
            );
            /*
             *  Create a protected directory to store keys in
             */
            if(!is_dir('history')) {
                mkdir('keys');
                $file = fopen('history/.htaccess','w');
                fwrite($file,"Generator");
                fclose($file);
            }
            /*
             *  Write the key key to the keys list
             */
            $file = fopen('history/keys','a');
            fwrite($file,"{$new}n");
            fclose($file);
        }
    }

现在一切正常,但我必须在运行之前自己输入这些文件。如何从目录中发布所有文件?现在我有这样的:

$PROTECTED_DOWNLOADS = array(
    array(
        'content_type' => 'application/png', 
        'suggested_name' => 'example.png', 
        'protected_path' => 'download/example.png'
    ),
    array(
        'content_type' => 'application/txt', 
        'suggested_name' => 'this_is_example.txt', 
        'protected_path' => 'download/this_is_example.txt'
    ),
    array(
        'content_type' => 'application/zip', 
        'suggested_name' => 'this_is_example.zip', 
        'protected_path' => 'download/this_is_example.zip'
    ),
    array(
        'content_type' => 'application/rar', 
        'suggested_name' => 'this_is_example.rar', 
        'protected_path' => 'download/this_is_example.rar'
    ),
    array(
        'content_type' => 'application/docx', 
        'suggested_name' => 'this_is_example.docx', 
        'protected_path' => 'download/this_is_example.docx'
    )
);

我尝试使用glob((,scandir((和readdir((,但我无法得到想要的结果。谢谢!

未测试,但可以尝试一下。

<?php
$directory = 'download';
$PROTECTED_DOWNLOADS = [];
foreach (glob($directory."/*") as $filename) {
    $PROTECTED_DOWNLOADS[]['content_type'] = mime_content_type($filename);
    $PROTECTED_DOWNLOADS[]['suggested_name'] = $filename;
    $PROTECTED_DOWNLOADS[]['protected_path'] = "$directory/$filename";
}
print '<pre>';
print_r($PROTECTED_DOWNLOADS);
print '</pre>';
?>

最新更新