将 URI 路由到 CakePHP 中的特定文件夹


Route URI to a specific folder in CakePHP

简介:

我的CakePHP中有这条路径:app/webroot/storage/5/C/_demo/omar.txt,这条路径将被重定向到http://localhost/storage/5/C/_demo/omar.txt

我的问题 :

我希望这条路径http://localhost/storage/5/C/_demo/omar.txt是这样的http://localhost/storage/uehKDj44/C/_demo/omar.txt,其中uehKDj44是5号,我这样做的原因是我不希望任何人将数字5更改为任何数字,因此他们无法访问否则他们先登录,假设如果5属于用户将被打开, 但如果不是不会开放,还有比这更好的方法来保护它吗?

谢谢

将受限数据存储为 htdocs 文件夹(或 CakePHP 的webroot(中的普通文件,无需进一步授权即可请求它们始终是一项有风险的业务,应避免。

我无法确定您在.txt文件中存储了哪种数据,但我假设它不是从数据库中获取然后保存的。我的理解是,文件的链接是向登录(授权(用户显示的。

提出更安全的解决方案:

  1. 将文件移出webroot文件夹,并创建一个具有该文件夹绝对路径的常量 ( USERDATA_PATH (。请记住为 Web 服务器用户设置读取权限(www-data 为 Apache 设置
  2. (
  3. 创建一个模型,例如 UserData底层数据库表存储用户和魔术哈希之间的关系(例如 1 => 'uehKDj44',2 => 'ds83skf' 等(。您还可以存储文件名以使其不那么复杂。
  4. 创建一个带有操作serveFile的控制器UserDataController,该控制器将密钥作为参数,将其与文件匹配并将文件输出给用户。
public function serveFile($hash= null) {
  try
  {
    $data = $this->UserData->findByHash($hash);
    if (!$data) {
      throw new Exception('No match found');  
    }
    // Load the data from file 
    $this->set('output', file_get_contents(USERDATA_PATH.DS.$data['UserData']['filename']));                   
  }
  catch (Exception $ex) 
  {
    // No match found - display error message / log
  } 
}

然后查看:

header('Content-type: text/plain'); 
echo $output;

这应该可以解决问题。