Custom URL routing with PHP and regex

痴心易碎 提交于 2019-11-30 16:14:28

问题


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:


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.

  • https://github.com/bramus/router
  • http://toroweb.org/
  • http://zaphpa.org/


来源:https://stackoverflow.com/questions/20179984/custom-url-routing-with-php-and-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!