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
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.