How to set up a single entry point architecture si

2019-02-11 08:31发布

Despite my efforts to find a tutorial on how to set up a secure, single entry point architecture for a web application built with PHP, I've not been able to find a good one. Who knows, maybe my search queries were bad... Looking at Laravel's code seemed like a good idea, but it's a good way to get your head spinning. There's just too much going on there for me to understand.

That being said, how would I go about for creating such an architecture that is both simple to apply to an app and secure (e.g. protect against local file inclusions) at the same time?

1条回答
Fickle 薄情
2楼-- · 2019-02-11 09:07

First of all, you need to redirect all your requests to a single PHP file. That part you do in .htaccess on Apache or it's counterparts on other servers.

Then you need to explore what data you can see in $_SERVER. It's quite common to use $_SERVER['PATH_INFO'], but the choice will depend on how exactly you rewrite the request.

Then you need to create a router, that has a list of regular expression and tries to match then against the URL fragment that you have acquired.

Here are few example that might give you some ideas:

  • '#^/(?P<page>[^/\\\\.,;?\n]+)$#'
  • '#^/user/(?P<id>[0-9]+)/(?P<nickname>[^/\.,;?\n]+)$#'
  • '#^(?:/test/(?P<parameter>[^/\\\\.,;?\n]+))?/mandatory$#'

It is common practice tho have these regular expressions generated from much simpler notations, but for the first iteration you should not focus on it too much.

Also, if you use expressions, that have optional fragments, you should also provide "fallback" values. These values would be used as defaults, if fragment is not provided, but pattern is matched.

The way I do it all looks like this in PHP:

/*
 * Routing mechanism
 */

$uri = isset( $_SERVER[ 'PATH_INFO' ] )
            ? $_SERVER[ 'PATH_INFO' ]
            : '/';

$builder = new RequestBuilder;
$request = $builder->create();
$request->setUri( $uri );

$router = new Router( new RouteBuilder );
$router->import(
    $reader->getAsArray( __DIR__ . '/config/routes.json' )
);

$router->route( $request );

After this the $request variable contains an object, which then you can query for specific parameter using commands like $id = $request->getParameter('id') or $controller = $request->getParameter('controller').

If you do not mess up with patterns themselves, then the values, that you extract will be safe against unauthorized file inclusions.

查看更多
登录 后发表回答