X-Send File

Found nice feature in Yii X-Send.

Here’s a flow.

Say you need to protect your images. So they shouldn’t be public available for all users. In this case you need to check user right and then return image.

If your application is highloaded, returning images for php could be expensive task. Yii provide ability to send images CHttpRequest->sendFile

$content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length) : substr($content,$contentStart,$length);

So you have to read file content. There’s another approach with fpassthru¬†function but looks like yii provide more accurate data for headers.

Anyway there is much simpler and elegant solution.

xSendFile

In this case server will do all the work for you. Everything is quite straightforward. The only one trick that I made is extension for nginx

 public function xSendFile($filePath, $options=array())
    {
        if (getenv('SERVER_NGINX')) {
            $options['xHeader'] = 'X-Accel-Redirect';
            $filePath = str_replace(\Yii::getPathOfAlias('root'), '', $filePath);
        }

        parent::xSendFile($filePath, $options);
    }

Ann to nginx config

location /uploaded/images {
internal;
root /var/mysite.com/;
}

Leave a Reply

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