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

时间:2018-04-08 07:41:05

标签: php arrays directory

我需要使用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(),但是我无法获得所需的结果。谢谢!

1 个答案:

答案 0 :(得分:2)

未经测试,但请尝试这样。

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