Deny the user's request to explore my website's directories/files

My problem might seem very basic, but i don't know how to search about this in google. I want my website's content to be reachable only trough global get variables. Like so..

<?php
        include("../backend/connection.php");
            if(isset($_GET['page'])){
                if ($_GET['page'] === "register"){
                    include ("pages/register.php");
                }
                elseif($_GET['page'] === "login"){
                    include ("pages/login.php");
                }
                elseif($_GET['page'] === "home"){
                    include ("pages/home.php");
                }
                
            }
?>

So, the user can access the register page trough "www.mywebsite.com?page=register". But he can also access that page using "www.mywebsite.com/pages/register.php". This is a problem. The connection file is included only in my index file. The register.php file contains code that requires a database connection, and since that database connection is included only in the index file, the user will get error. Trough that error he will get information about my website directories, and he might try to continue digging until he finds a hole.

I think the following code might fix the problem.

<?php
        include("../backend/connection.php");
            if(isset($_GET['page'])){
                if ($_GET['page'] === "register"){
                    include ("pages/register.php");
                }
                elseif($_GET['page'] === "login"){
                    include ("pages/login.php");
                }
                elseif($_GET['page'] === "home"){
                    include ("pages/home.php");
                }
            }elseif(!isset($_GET['page'])){
            header("www.mywebsite.com?page=home");
            }
?>

I consider that code a quick fix, but i know that there is a better way for me to do this, i need some advice.

Upvotes: 1

Views: 59

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

Move the folder pages outside the document root and load them with:

include ("../pages/register.php");

just like you do with ../backend/connection.php.

That way, no one can access them directly from the outside through the web server, but will still be accessible in your PHP code. You also don't need to check if some constant is defined on all your pages.

This is also how most modern frameworks do it. They only have an index.php-file in the web root and all the other code outside (including views)

Upvotes: 2

Roman Angelovskij
Roman Angelovskij

Reputation: 71

You can define constant, for example

define('APP_LOADED', true);

in included scripts check that constant is defined and exit if not

if (!defined('APP_LOADED')){
   exit();
}

Upvotes: 1

Related Questions