Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - How to list the files inside a folder

Tags:

file

php

list

yii

yii2

Hi, i'm making an Yii2 Basic application and have a file upload form in the admin area. The file upload sends files to app/web/uploads. I followed the great tutorial on uploading files from samdark. It can be seen here: https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

What i need to do is to create a view that renders hyperlinks to each one of the files inside uploads folder.

In Yii1.xx there was an extension for handling files called Cfile very handy. I used in several applications to do what i want now.

Using Cfile i was able to write code like this:

$cfileDir = Yii::app()->file->set('pdfs/'); // set pdfs as target folder

$files = $cfileDir->getContents();

The getContents() method was great because it let me later apply a foreach loop and list all the files in the folder.

In Yii2 how to do something similar in uploads folder, ie, list of files in that folder and create hyperlinks in a view.

To crate the hyperlinks inside the view i could use Html::a(), but to get all the files inside it i don't know how to do it.

Any Ideas ?? Thanks.

EDIT

SOLVED with the great tip from ALI.

HERE IS THE COMPLETE BLOCK OF CODE

<?php
    $files=\yii\helpers\FileHelper::findFiles('uploads/');
    if (isset($files[0])) {
        foreach ($files as $index => $file) {
            $nameFicheiro = substr($file, strrpos($file, '/') + 1);
            echo Html::a($nameFicheiro, Url::base().'/uploads/'.$nameFicheiro) . "<br/>" . "<br/>" ; // render do ficheiro no browser
        }
    } else {
        echo "There are no files available for download.";
    }
?>
like image 470
André Castro Avatar asked Dec 08 '14 21:12

André Castro


1 Answers

In Yii2 you can achieve this by using FileHelper Class like below:

$files=\yii\helpers\FileHelper::findFiles('/path/to');

Now, you have all files list into $files variable as an array.

findFiles() method, returns the files found under the specified directory and sub-directories.

Another examples:

\yii\helpers\FileHelper::findFiles('.',['only'=>['*.php','*.txt']]);

Above example lists all files only with php and txt extensions.

\yii\helpers\FileHelper::findFiles('.',['except'=>['*.php','*.txt']]);    

Above example lists all files with all extensions, except php and txt extensions.

\yii\helpers\FileHelper::findFiles('.',['recursive'=>FALSE]);

Above example does not list files under the sub-directories

like image 160
Ali MasudianPour Avatar answered Oct 24 '22 00:10

Ali MasudianPour