You could simply use Assets and Aliases for this:
If you have a backup/web/uploads/
folder in which you save images uploaded via your backend and you'd like to display those images on your frontend.
Create a new asset file in your frontend/assets/
, let's call it BackendAsset.php:
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
class BackendAsset extends AssetBundle {
public $sourcePath = '@backend/web/uploads';
}
where $sourcePath
is the backend-folder (source) you'd like to access on the frontend. The @backend alias is predefined in the advanced template, so we'll use it.
Now in our view we can simply use the BackendAsset:
<?php
use frontend\assets\BackendAsset;
$backend = BackendAsset::register($this);
?>
and now we can easily display a file, let's say backend/web/uploads/somefile.jpg
:
<img src="<?= $backend->baseUrl . '/somefile.jpg' ?>" >
NOTE: Using the asset in this way copies all the files from the backend/web/uploads
to an asset folder in the frontend. To prevent that, you can tell your application not to copy the files, but to link to them (creating SymLinks) instead, unsing linkAssets
(yii2 docu):
In your app configuration (in this case frontend/config/main.php
), set the linkAssets
parameter to TRUE:
'components' => [
'assetManager' => [
'linkAssets' => true,
]
]