19 laravel laravel-5 laravel-5.1 laravel-5.2 laravel-5.3
我已经安装了Laravel 5.0并进行了身份验证.一切都很好.
我的网站仅对经过身份验证的成员开放.内部内容仅受Authenticated成员保护,但站点内的图像不受公共视图保护.
任何人直接写图像URL都可以看到图像,即使该人没有登录到系统.
http://www.somedomainname.net/images/users/userImage.jpg
Run Code Online (Sandbox Code Playgroud)
我的问题:是否可以从公共视图保护图像(上面的URL示例),在其他Word中,如果图像的URL发送给任何人,则个人必须是成员并且登录才能看到图像.
这可能吗?怎么样?
may*_*ʎɐɯ 30
可以在Laravel 5.x文件夹中保护图像免受公共视图的影响.
在Laravel中创建images
文件夹下的storage
文件夹(我选择了storage
文件夹,因为它在我上传图像时已经具有写入权限)storage/app/images
.
将要保护的图像从公用文件夹移动到新创建的images
文件夹.您也可以选择其他位置来创建images
文件夹但不在公共文件夹中,但是在Laravel文件夹结构中但仍然是逻辑位置示例不在控制器文件夹内.接下来,您需要创建路径和图像控制器.
创建路线
Route::get('images/users/{user_id}/{slug}', [
'as' => 'images.show',
'uses' => 'ImagesController@show',
'middleware' => 'auth',
]);
Run Code Online (Sandbox Code Playgroud)
如果此人未登录,路由将转发所有图像请求访问身份验证页面.
创建ImagesController
class ImagesController extends Controller {
public function show($user_id, $slug)
{
$storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
return Image::make($storagePath)->response();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以根据需要修改存储路径和文件/文件夹结构,这只是为了演示我是如何做到的以及它是如何工作的.
您还可以添加条件以仅显示控制器中特定成员的图像.
此外,还可以使用文件名,时间戳和其他变量来散列文件名.
另外:有些人询问这种方法是否可以用作公共文件夹上传的替代方法,是的,这是可能的,但不建议按照本答案中的说明进行练习.因此,即使您不打算保护它们,也可以使用相同的方法在存储路径中上传图像,只需按照相同的过程进行删除即可'middleware' => 'auth',
.这样,您就不会在公共文件夹中授予777权限,并且仍然拥有安全的上传环境.同样提到的答案也解释了如何使用这种方法进行身份验证,以防有人使用它或提供替代解决方案.
Abd*_*lol 10
在以前的项目中,我通过执行以下操作来保护上传:
创建的存储磁盘:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
Run Code Online (Sandbox Code Playgroud)
这将上传公众\storage\app\uploads\
无法查看的文件。
要在控制器上保存文件:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
Run Code Online (Sandbox Code Playgroud)
为了让用户查看文件并防止未经授权的访问上传。首先检查磁盘上是否存在该文件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
服务的文件,如果用户有权访问:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
最后在Web.php路由上:
Route::get('uploads/user-files/{filename}', 'MiscController@licenceFileShow');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14917 次 |
最近记录: |