Skip to content

Instantly share code, notes, and snippets.

@samdark
Created February 16, 2023 07:02
Show Gist options
  • Save samdark/e673a2c5de2bfc556e4b6b1e46f028cf to your computer and use it in GitHub Desktop.
Save samdark/e673a2c5de2bfc556e4b6b1e46f028cf to your computer and use it in GitHub Desktop.
Yii3: Sending a file

Here's how to currently send a file with Yii3 in the most efficient way. We need to think about where to put such code not to write it every time.

<?php

declare(strict_types=1);

namespace App\Controller;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Http\ContentDispositionHeader;
use Yiisoft\Http\Header;

final class SiteController
{
    public function __construct(
        private ResponseFactoryInterface $responseFactory
    )
    {
    }
    
    private function sendFile(
        string $filePath,
        ?string $attachmentName,
        ?string $disposition,
        ?string $mimeType,
        ?string $xHeader
    ): ResponseInterface
    {
        if ($attachmentName === null) {
            $attachmentName = basename($filePath);
        }

        if ($mimeType === null) {
            $info = new \finfo(FILEINFO_MIME_TYPE);
            $mimeType = @$info->file($filePath) ?: null;

            if ($mimeType === null) {
                $mimeType = 'application/octet-stream';
            }
        }

        $dispositionHeader = ContentDispositionHeader::value(
            $disposition ?? ContentDispositionHeader::ATTACHMENT,
            $attachmentName
        );

        return $this->responseFactory
            ->createResponse()
            ->withHeader($xHeader ?? 'X-Sendfile', $filePath)
            ->withHeader(ContentDispositionHeader::name(), $dispositionHeader)
            ->withHeader(Header::CONTENT_TYPE, $mimeType);
    }
    
    public function test(): ResponseInterface
    {
        return $this->sendFile('~/test.jpg');
    }
}
@samdark
Copy link
Author

samdark commented Feb 20, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment