【问题标题】:How to restrict some users and public from accessing uploaded files using php yii framework如何使用 php yii 框架限制部分用户和公众访问上传的文件
【发布时间】:2015-01-02 13:52:34
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: php file-upload yii privileges yii-extensions


    【解决方案1】:

    为防止任何人访问上传文件夹中的文件,请在其中放置一个.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2014-06-29
      • 1970-01-01
      • 2016-03-20
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多