Load other files (from outside public_html) under index.php I wanted to load every page under index.php with a simple index.php?do=login

For example when the link index.php?do=login or /login/ is opened, the file login.php is loaded (from outside public_html), and so everything is done under index.php instead of having a separate php file in public_html for each action!

This is what I've tried already, am I doing it okay? (I'm not sure if what I'm doing has any security vulnerabilities, so please kindly advise)

index.php

&lt;?php

// application path (outside public_html)
define('FILESPATH', APP.'../application/actions/');

// Default file
$file_name = 'home_page';

// e.g. index.php?do=login or /login/
if(isset($_GET['do'])){
    $file_name = rtrim($_GET['do'],'/');
}

// Set file path
$fpath = FILESPATH."{$file_name}.php";

// Make sure user input has valid characters a-z 0-9 _
if(preg_match('/^[A-Za-z0-9_]+$/', $file_name) !== 1 OR ! file_exists($fpath)){
    // Error
    require_once('404.php');
    die();
}

// Load the do=file
require_once($fpath);

// Nothing more comes in index.php


login.php

&lt;?php

// Load template file header
require_once('header_template.php');


//
// Stuff that happens in login.php
// Checking if $_POST['username'] has valid chars then searching for it with pdo in db,
// password_verify() for $_POST['password'], etc...
//


// Load login's html template 
// (which includes the html form submitted to /login/)
require_once('login_template.php');

// Load template footer
require_once('footer_template.php');


.htaccess

To run with site.com/login/ etc instead of site.com?do=login

&lt;IfModule mod_rewrite.c&gt;
    RewriteEngine On
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteRule   ^((?s).*)$ index.php?do=$1 [QSA,L]
&lt;/IfModule&gt;
You can simplify your regex pattern and you might like to combine your validation with the preparation step.  The following pattern is just like yours except it allows a single trailing slash and omits it from the capture group.

if (isset($_GET['do']) &amp;&amp; preg_match('~^(\w+)/?$~', $_GET['do'], $valid)) {
    $file_name = $valid[1];
} else {
    $file_name = "home_page";
}

$fpath = FILESPATH . "{$file_name}.php";

if (!file_exists($fpath)) {
    // Error
    require_once('404.php');
    die();
}


It doesn't make sense to valid home_page with your pattern, you know it will pass every time. I suppose it could be possible that your home_page file may not exist in the directory.