拒绝要查看的文件夹,除非经过身份验证并访问网站根目录外的文件夹

时间:2014-07-04 17:56:38

标签: php .htaccess authentication

我有点困惑。我在root / website中有一个网站(Apache),在我的主页面上有一个身份验证表单,如果用户可以获得身份验证,则在提交服务器时使用LDAP检查。

成功后,应将用户重定向到' root / website / filestoview'的文件夹视图。并且能够在里面导航/下载。

  1. 如果用户经过身份验证并拒绝任何类似www.mysite.com/filestoview的尝试,我该如何实现重定向?

    我试过htaccess:

    order deny,allow
    allow from localhost
    deny from all
    but didn't work.
    
  2. 如何在我的根网站之外的文件夹中显示内容(FTP,即导航/下载的可能性)?我尝试从根../../folder2但它继续将我重定向到主页面。

  3. 谢谢

1 个答案:

答案 0 :(得分:1)

允许授权用户浏览和下载public_html

之外的文件
<?php 
// Allow authorized users to browse and download files outside public_html
// http://stackoverflow.com/users/1310701/hex494d49

if(is_user_authorized($user)){
    // at this point the user has been authorized
    // this is the protected directory; it is outside of public_html

    // this is the protected directory
    $home = $dir = '/home/user-root/member-area/';

    // prevent hacking :)
    if(isset($_GET["handle"]) && strpos($_GET["handle"], $home) !== false){
        if(is_dir($_GET["handle"])){
            $dir = $_GET["handle"] . "/";
        }else if(is_file($_GET["handle"])){
            $file = $_GET["handle"];
            // let user download the file
            download_file($file);
        }
     }

     // add <back> link if we are within some sub-directory
     echo ($dir != $home) ? "<a href='?handle=" . dirname($dir) ."'>back</a><br />" : "";

     // scan directory
     $entries = scandir($dir);
     $length = count($entries);
     for($i = 0; $i < $length; $i++){
         if($entries[$i] != "." && $entries[$i] != "..") {
             echo "<a href='?handle=" . $dir . $entries[$i] . "'>" . $entries[$i] . "</a><br />";
         }
      }
}else{
    // user isn't authorized to view the content so 
    // redirect her/him to something entertaining :) 
    header("Location: https://disneyland.disney.go.com");
}

// -----
function is_user_authorized($user){
    // ... your authorization code
    return ($user) ? true : false;  
}

// -----
function download_file( $file_name ){
    if(!file_exists($file_name)) return false;
    header("Content-Description: File Transfer");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; file_name = " . basename($file_name));
    header("Content-Transfer-Encoding: binary");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: public");
    header("Content-Length: " . filesize($file_name));
    ob_clean();
    flush();
    readfile($file_name);
    exit;
}

?>

进一步改进:添加filetype和filesize,使用base64编码/解码句柄,提高安全性