如何限制一些用户和公众使用php-yii框架访问上传的文件


How to restrict some users and public from accessing uploaded files using php yii framework

我已经使用Yii创建了一个php应用程序。它有用户、公共和管理模块。

在上传文件时,用户应该能够设置访问权限(例如公共、私有、特定组等)。

我想限制人们通过URL访问文件。

  • 我该如何解决这个问题?

  • Yii是否为此提供了任何内置机制?

要防止任何人访问上传文件夹中的文件,请在中放置一个.htaccess文件

deny from all

然后,为了允许某些用户访问该文件,创建一个控制器操作:

private function actionDownload($fileId) {
    $file = File::model()->findByPk(fileId);
    $filePath = Yii::app()->basePath.'/../uploads/'.$file->filename;
    // Check user permissions
    if($file->permissions != 'public' && $file->userId != Yii::app()->user->id)
        throw new CHttpException(404, 'This file does not belong to you.');
    // Download file to user
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $filePath);
    finfo_close($finfo);
    $size = filesize($filePath);
    header("Content-Type: ".$mime);
    header("Content-Length: ".$size);
    header("Content-Disposition: attachment; filename='"".$fileName."'"");
    readfile($filePath);
    exit;
}

示例URL,取决于您的首选设置:

http://example.com/download/1
http://example.com/site/download/1
http://example.com/site/download?fileId=1