Using Yii aliases

Aliases are used to represent file paths or URLs so that you don’t have to hard-code absolute paths or URLs in your project. An alias must start with the @ character to be differentiated from normal file paths and URLs. Alias defined without leading @ will be prefixed with @ character.

Yii has many pre-defined aliases already available. For example, the alias @yii represents the installation path of the Yii framework; @web represents the base URL for the currently running Web application.[Adapted from Yii guide]

In this example you will learn how to use aliases to read files from a certain directory in your app.

First set an alias using Yii:setAlias method in common/config/bootstrap.php

Yii::setAlias('@shopfolders', dirname(dirname(__DIR__)). '/uploads/');


Now we can access the alias anywhere in the app using Yii:getAlias(@shopfolders)

Add a controller action that will handle the reading of folders

public function actionDetails()
    $dir = Yii::getAlias('@shopfolders').'/';
    $files = array();
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               // echo 
                //$files[]['filename'] = $file;
                //$files[]['filetype'] = filetype($dir . $file);
                if ($file != '.' && $file != '..') {
                    $files[] = array('filename' => $file,
                    'filetype' => filetype($dir . $file)

    return $this->render('details',[


The view file

/* @var $this yii\web\View */
foreach ($files as $file) {
  echo "<li>".$file['filename']."    ". $file['filetype']."</li>";


That is it! 🙂

Example of output

Get Yii 2 RESTful guide

Leave a Reply

Your email address will not be published. Required fields are marked *