laravel - 如何在 Laravel 5 中保护图像不被公众看到?

标签 laravel laravel-5 laravel-5.2 laravel-5.1 laravel-5.3

我已经安装了 Laravel 5.0 并进行了身份验证。一切正常。

我的网站只对经过身份验证的成员(member)开放。内部的内容仅对经过身份验证的成员提供保护,但站点内部的图像不 protected 以供公众查看。

任何人直接写入图片 URL 都可以看到图片,即使该人没有登录系统。

http://www.somedomainname.net/images/users/userImage.jpg

我的问题:是否可以保护图像(上面的 URL 示例)不被公众查看,换句话说,如果图像的 URL 发送给任何人,则个人必须是成员(member)并登录才能看到图像。

这可能吗?怎么做?

最佳答案

在以前的项目中,我通过执行以下操作来保护上传:

已创建 存储盘 :

config/filesystems.php
'myDisk' => [
        'driver' => 'local',
        'root' => storage_path('app/uploads'),
        'url' => env('APP_URL') . '/storage',
        'visibility' => 'private',
    ],

这会将文件上传到 \storage\app\uploads\ 不可用公众 观看。

要在 Controller 上保存文件:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);

为了让用户查看文件并保护上传内容免受 未经授权的使用权。首先检查文件存在在磁盘上:
public function returnFile($file)
{
    //This method will look for the file and get it from drive
    $path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
    try {
        $file = File::get($path);
        $type = File::mimeType($path);
        $response = Response::make($file, 200);
        $response->header("Content-Type", $type);
        return $response;
    } catch (FileNotFoundException $exception) {
        abort(404);
    }
}

服务如果用户具有正确的访问权限,则该文件:
 public function licenceFileShow($file)
{
    /**
     *Make sure the @param $file has a dot
     * Then check if the user has Admin Role. If true serve else
     */
    if (strpos($file, '.') !== false) {
        if (Auth::user()->hasAnyRole(['Admin'])) {
            /** Serve the file for the Admin*/
            return $this->returnFile($file);
        } else {
            /**Logic to check if the request is from file owner**/
            return $this->returnFile($file);
        }
    } else {
//Invalid file name given
        return redirect()->route('home');
    }
}

最后在 Web.php 路线:
Route::get('uploads/user-files/{filename}', 'MiscController@licenceFileShow');

关于laravel - 如何在 Laravel 5 中保护图像不被公众看到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682421/

相关文章:

php - Laravel 事件模拟

php - 如何通过 Laravel 5.2 中的 ajax 请求将 Json 数组中的数据插入数据库

php - Laravel 5.2 中的 Elasticsearch

laravel-5.2 - Laravel 5 中创建策略的问题

laravel - 如何使用相同的名称再次创建已删除的 Controller ?

php - laravel 表单请求 = 如果按钮被点击

php - ElasticSearch 查询卡在 laravel 作业队列中

php - 我如何在注册期间为用户分配角色? (委托(delegate))(Laravel 5.1)

php - 如何在laravel 5.2中为连接表执行sql计数功能

laravel - 队列 worker :queue-worker_00: ERROR (spawn error) Laravel Supervisor CentOS 7