user1453094
user1453094

Reputation: 373

RegEx Error in Router

Update

When I go to /about/, I get:

Route: contact
Get Param: about

When I go to /contact/, I get:

Route: about
Get Param: contact


Here's my code:

foreach ($routes as $route) {
            if (preg_match('/^' . $route . '$/', $uri)) {
                $controller = 'controllers/' . $route . '.php';

                if (file_exists($controller)) {
                    include_once($controller);
                } else {
                    echo '<h1>404 - Missing Controller</h1>';
                }
            } else {
                echo '<h1>404 - Missing Route</h1>';
            }
}

Problem is, I'm always seeing "Missing Route"... what's my problem here?

I get the same problem if I replace the preg_match with if ($uri == $route)

$routes = Array ( [0] => about [1] => contact )
$uri = contact

Directory structure:

controllers/
      About.php
      Contact.php
Router.php

Thanks for your help!

Upvotes: 0

Views: 96

Answers (2)

abhi.gupta200297
abhi.gupta200297

Reputation: 891

Your else condition is executing for every index except the matching one.

What i think you need to do is:

if(in_array($uri, $routes) {
            $controller = 'controllers/' . $uri . '.php';
            if (file_exists($controller)) {
                include_once($controller);
            } else {
                echo '<h1>404 - Missing Controller</h1>';
            }
 } 
 else {
            echo '<h1>404 - Missing Route</h1>';
      }

Also, if your controller names start with Capital letters, you need to add some logic to the making $controller variable to that it capitalizes the first character.

Upvotes: 1

Andy Lester
Andy Lester

Reputation: 93676

Why are you using preg_match at all?

if (preg_match('/^' . $route . '$/', $uri))

is the same as

if ($route == $uri)

unless for some reason you want your $route to have regular expression metacharacters in it.

Also, your output says you have a 404, but are you actually returning an HTTP response of 404?

Upvotes: 1

Related Questions