Home > Mobile >  Php header location outside of web root
Php header location outside of web root

Time:01-27

I have a login page and a member page.

login.php page in website root:

 include(ROOT_PATH.'server.php') ;//outside of web root

 ... login form:

<form method="post" action="login.php">

    <div >
        <label>username </label>
        <input type="text" name="username">
    </div>

    <div >
        <label>Password</label>
        <input type="password" name="password" autocomplete="new-password">
    </div>

    <div >
        <button type="submit"  name="login_user">Login</button>
    </div>

</form>

server.php

// LOGIN USER
   if (isset($_POST['login_user'])) {

   $username = $_POST['username'];
   $pass = $_POST['password'];


   //sanitize, check with database

   //if password valid, redirect to member page

    $_SESSION['username'] = $username;
    $_SESSION['user_id'] = $user_id;

    header('location:'.BASE_URL.'member.php');
    exit;

}

My questions:

  1. I wanted to place member.php outside of web root but I dont know if header('location.. can access as such?

  2. If member.php has to be in web root, how can I protect access to this page more that curently is?

member.php

session_start(); 

if (!isset($_SESSION['username']) && !isset($_SESSION['user_id'])) {
    header('location:login.php');
    exit;
}

... rest of the code

CodePudding user response:

I wanted to place member.php outside of web root

If you place the file member.php outside the web root, then nobody will be able to access the URL /member.php, even if they are authenticated.

but I dont know if header('location.. can access as such?

Location headers point to URLs, not to files. So, if the URL you're trying to redirect to is not reachable by anybody (because you moved its associated file outside the web root), then the redirect will always bring everybody to a 404.

If member.php has to be in web root, how can I protect access to this page more that curently is?

Redirecting back to the login page when there's no session (like you're already doing) is generally how this situation is handled and should be sufficient for simple purposes. The main downside to this method is that you have to be vigilant and remember to explicitly put this check in every single source file in your web root.

Beyond that, you might explore the front controller pattern, which most MVC frameworks provide. This funnels all application access through one single control point, and would allow you to put the source files for your business logic, configuration, and templating outside the web root.

  • Related