Reputation: 33
I need help with router when i enter route in href for example
first link i click works url is localhost/account/login
but second time i click link url is localhost/account/account/register
function __construct(){
$arr = require 'application/config/routes.php';
foreach ($arr as $key => $val) {
$this->add($key, $val);
}
}
public function add($route, $params) {
$route = '#^'.$route.'$#';
$this->routes[$route] = $params;
}
public function match() {
$url = trim($_SERVER['REQUEST_URI'], '/');
foreach ($this->routes as $route => $params) {
if (preg_match($route, $url, $matches)) {
$this->params = $params;
return true;
}
}
return false;
}
public function run(){
if($this->match()){
$path = 'application\controllers\\'.ucfirst($this->params['controller']).'Controller';
if(class_exists($path)){
$action = $this->params['action'].'Action';
if (method_exists($path, $action)){
$controller = new $path($this->params);
$controller->$action();
}else{
View::errorCode(404);
}
}else{
View::errorCode(404);
}
}else{
View::errorCode(404);
}
}
Upvotes: 1
Views: 841
Reputation: 432
Your URL's don't start with /
, so they are relative to the current URL. Please add a /
before.
Your code now:
<a href="account/register">Register</a>
Change it to:
<a href="/account/register">Register</a>
Upvotes: 4