在index.php下加载其他文件(来自public_html之外)

问题描述 投票:0回答:1

我想用一个简单的index.php?do=login加载index.php下的每个页面

例如,当链接index.php?do=login/login/被打开时,文件login.php被加载(来自public_html之外),所以一切都在index.php下完成,而不是在public_html中为每个动作都有一个单独的php文件!

这是我已经尝试过的,我做得好吗? (我不确定我所做的是否有任何安全漏洞,所以请提出建议)

的index.php

<?php

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

// Default file
$file_name = 'home_page';

// e.g. index.php?do=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
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

<?php

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


//
// Stuff that happens in login.php
// Like checking if username has valid characters then searching for it with pdo in db,
// password_verify(), etc...
//


// After the stuff done above load login html template
require_once('login_template.php');

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

的.htaccess

site.com/login/等而不是site.com?do=login一起运行

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond   %{REQUEST_FILENAME} !-d
    RewriteCond   %{REQUEST_FILENAME} !-f
    RewriteRule   ^((?s).*)$ index.php?do=$1 [QSA,L]
</IfModule>
php .htaccess
1个回答
0
投票

听起来你正在寻找的是路由器。我建议你不要重新发明轮子,而应该看看已经看过一些用法和测试的现有轮子。

Respect/Rest重量轻,功能多样且易于使用。

use Respect\Rest\Router;

$r3 = new Router('/index.php');

// endpoint: /index.php/
$r3->get('/', function() {
    return 'Hello World';
});

// endpoint: /index.php/login
$r3->any('/login', function() {
    // use $_POST data to validate user
    return 'Login Success';
});

// endpoint: /index.php/item/123
$r3->get('/item/*', function($id) {
    $item = $db->fetchItem($id);
    return json_encode($item);
});

没有比那更容易... nJoy!

© www.soinside.com 2019 - 2024. All rights reserved.