【问题标题】:Can't access static files where php_flag engine off无法访问 php_flag 引擎关闭的静态文件
【发布时间】:2016-05-26 18:19:19
【问题描述】:

我有一个 Laravel Web 应用程序,它允许人们将他们的文件上传到 uploads 目录。 我想允许任何文件类型和名称,但不允许执行它们(只是静态文件上传/下载),所以我创建了一个 .htaccess 文件:

/public_html/uploads/.htaccess:

php_flag engine off

但是当我尝试访问存储的文件(例如 /uploads/photo.jpg)时,Laravel 会提供一个 NotFoundHttpException。 如果我在行前加上#,我可以访问文件,但随后执行 php 脚本。

这是 Laravel 的 htaccess 文件

/public_html/uploads/.htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

【问题讨论】:

    标签: php apache .htaccess laravel


    【解决方案1】:

    您可以使用file_get_contents($filename) 获取文件的内容,然后使用application\octect-stream 标头将文件作为直接静态下载发送。

    $fileContent = file_get_contents($fullPathToFile);
    header('Content-Type: application/octet-stream');
    echo $fileContent;
    

    使用 Laravel,您始终可以使用内置方法:

    https://laravel.com/docs/master/responses#file-downloads

    供参考:

    $name = 'theFileName.txt'; 
    // You can override the name of the downloaded file
    
    $headers = ['Content-Type'=>'application/octet-stream',]; 
    // Sends a header saying the type is binary and should be accepted as such
    
    // Fires off PSR-7 compatible response from Laravel
    return response()->download($pathToFile, $name, $headers);
    

    我希望这会有所帮助!

    【讨论】:

    • 谢谢,这不会增加服务器的额外开销吗?因为 php 进程应该一直运行,直到客户端得到最后一点。而且在大文件上,php 最大执行时间可能不够
    • 虽然你说的是真的@Webinan,但你可以在该区域周围使用set_time_limit(int) 来获得所需的功能。使用 Laravel 的内置帮助程序发送文件的开销最小。 Apache 将始终执行通过它请求的 PHP 文件,除非 PHP 已关闭,或者您在第一次将文件内容读入缓冲区后将文件作为二进制内容发送。
    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 2013-10-01
    • 2018-08-31
    • 1970-01-01
    • 2014-04-08
    • 2015-04-19
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多