In your Yii2 controller it is quite common practice to return the stream of a file to the browser for your user to download.
However, it’s not so well documented you can set any stream reference as the content of your response.
In this scenario we want to have a file behind yii2 authentication that only some users can view. We could use the
1 | sendFile |
function to send a file stream to the browser. This will prompt the user to download the file. In this situation we just want the users to view the files.
This is where the
1 | stream |
property of the Yii2 response comes in. With this bit of code it will send the stream as the content of your response. The below code is a snippet will send a PNG file reference to the browser without using the
1 | file_get_contents |
function where we will be loading the full content of the file into memory rather than reading the file line by line.
1
2
3
4
5
6 public function actionViewFile(): void
{
Yii::$app->response->format = Yii::$app->response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'image/png');
Yii::$app->response->stream = fopen('/path/to/my.png', 'rb');
}
The stream property of the response can also be the stream from the
1 | flysystem |
fs adapter, so we can stream our files from s3 straight to the browser. Below is a snippet using yii2 flysystem to connect to an aws s3 bucket.
1
2
3
4
5
6 public function actionViewFile(): void
{
Yii::$app->response->format = Yii::$app->response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'image/png');
Yii::$app->response->stream = Yii::$app->fs->readStream('my.png');
}
More reads
The Invisible Design Paradox: Why Beautiful Websites Don’t Always Succeed
There’s a persistent myth in digital strategy that equates aesthetic appeal with business success. The thinking goes that a beautiful website naturally translates into a successful one. The reality, however, is more nuanced.
Q3 Project updates
As a small yet busy web agency we often have little time to shout about what we are up to, and also work on secret projects we are unable to tell you about. Here’s a snapshot of what we’ve been working on…
[updated] Diagrams to live your life by
As part of our Practically Academy Sam shared a whole series of diagrams that help in the strategy work that he does, and beyond.



![[updated] Diagrams to live your life by](https://b2209735.smushcdn.com/2209735/wp-content/uploads/DiagramsTLYLB-Choice-vs-happiness-paradox-400x250.jpg?lossy=2&strip=1&webp=1)