I have written a basic Router class for my MVC, however I'm having trouble to use hyphen in my links, it gives a 403 Forbidden for existing links, however for non-existing ones it prints them out correctly and gives a 404 error page.
My controller classes are of the form Link_Here and I change the hyphen to underscore in the router. The URL structure is http://example.com/{$controller}/($action)/($parameters) and the issue is the controller part
Here's my router code:
<?php
class Router
{
private $url, $controller, $method, $params;
private $allowedChars = array('-', '_', '/', '\\', '.');
public function __construct()
{
if(!empty($_GET['page']))
{
if(ctype_alnum(str_replace($this->allowedChars, '', $_GET['page'])))
{
$this->url = $_GET['page'];
}
else
{
throw new Exception("Malformed URL");
}
}
else
{
$this->url = 'index';
}
$this->url = explode('/', $this->url);
// This is where I change the hyphen to an underscore
$this->controller = implode('_', array_map('ucfirst', explode('_', str_replace('-', '_', array_shift($this->url)))));
$this->method = array_shift($this->url);
$this->params = &$this->url;
}
public function commit()
{
if(class_exists($this->controller))
{
if(method_exists($this->controller, $this->method) && empty($this->params))
{
if(empty($this->params))
{
$ctrl = new $this->controller;
$ctrl->loadModel($this->controller);
$ctrl->{$this->method};
}
else
{
$ctrl = new $this->controller;
$ctrl->loadModel($this->controller);
$ctrl->{$this->method}($this->params);
}
}
else
{
$ctrl = new $this->controller;
$ctrl->loadModel($this->controller . '_Model');
$ctrl->index();
}
}
else
{
$ctrl = new Error;
$ctrl->loadModel('Error');
$ctrl->notFound();
}
}
}
And my rewrite rules:
<IfModule mod_rewrite.c>
Options +FollowSymlinks
# Options +SymLinksIfOwnerMatch
Options -Indexes
RewriteEngine On
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
</IfModule>