Custom URL routing with PHP and regex

2019-02-15 15:26发布

I'm trying to create a very simple URL routing, and my thought process was this:

  • First check all static URLs
  • Then check database URLs
  • Then return 404 if neither exists

The static URLs are easy to do of course, but I'm trying to figure out the best way to do dynamic ones. I would prefer not to have to set a static prefix, despite knowing that it would make this a lot easier to code.

This is what I currently have:

$requestURL = $_SERVER['REQUEST_URI'];

if ($requestURL == '/') {
    // do stuff for the homepage
}

elseif ($requestURL == '/register') {
    // do stuff for registration
}

// should match just "/some-unique-url-here"
elseif (preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) { 
    // query database for that url variable
}

// should match "/some-unique-url/and-another-unique-url"
elseif (preg_match("(^\/[A-Za-z0-9\-]+\/[A-Za-z0-9\-]+)/",$requestURL)) {
    // query database for first and second variable
}

else {
    // 404 stuff
}

My problem is that if I have "/register" URI, it will match the second elseif statement as well as the regex statement. But I want to avoid having to specifically exclude each static URL from regex statement, such as this:

// should match just "/some-unique-url-here"
elseif ((preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) &&
    ($requestURL !== '/register') &&
    ($requestURL !== '/')) { 
    // query database for that url variable
}

What's the easiest way to solve this problem? I'll probably have like 15-20 static URLs, so specifically excluding all of them would be very clunky.

1条回答
相关推荐>>
2楼-- · 2019-02-15 16:12

Your problem does not exist. If the first elseif ($requestURL == '/register') matches, all subsequent elseifs on the same level won't get evaluated.

You're already doing it right, just make sure you do the string comparisons (==) first.

On another note, don't reinvent the wheel.

查看更多
登录 后发表回答