how to protect server directory using .htaccess

前端 未结 5 1663
-上瘾入骨i
-上瘾入骨i 2021-02-10 21:02

I have designed a website, and within it I have a range of PHP scripts which interact with my system. For example, if a user uploads an image, this is processed by the script

5条回答
  •  清歌不尽
    2021-02-10 21:52

    Blocking files with htaccess makes the files inaccessible to the requestor, e.g. the visitor of the page. So you need a proxy file to pass the visitor's request to the files. For that, have a look at the MVC pattern and the Front Controller pattern.

    Basically, what you will want to do is route all requests to a single point of entry, e.g. index.php and decide from there, which action(your scripts) is called to process the request. Then you could place your scripts and templates outside the publicly accessible folder or, if that is impossible (on some shared hosts), protect the folders with htaccess like you already did (DENY FROM ALL) then.

    To use the upload script you'd have a URL like http://example.com/index.php?action=upload.

    A supersimple FrontController is as easy as

    $scriptPath      = 'path/to/your/scripts/directory/';
    $defaultAction   = 'action404.php';
    $requestedAction = $_GET['action']; // you might want to sanitize this
    
    switch($action) {
        case 'upload':
            $actionScript = 'image.php';
            break;
        case 'login':
            $actionScript = 'login.php';
            break;
        default:
            $actionScript = $defaultAction;
    }
    include $scriptPath . $actionScript;
    exit;
    

    Your actionScript would then do everything you need to do with the request, including redirection, db access, authentication, uploading stuff, rendering templates, etc - whatever you deem necessary. The default action in the example above could look like this:

    There is numerous implementations of the FrontController pattern in PHP. Some simple, some complex. The CodeIgniter framework uses a lightweight MVC/FrontController implementation that might not be too overwhelming if this is new to to you.

    Like Atli above suggested, you could use mod_rewrite to force all requests to index.php and you could also use it to pretty up your URLs. This is common practice with MVC frameworks and has been covered extensively here and elsewhere.

提交回复
热议问题