P
P
Platton2015-11-27 14:32:53
PHP
Platton, 2015-11-27 14:32:53

Creating a php router. Another way to parse url?

Hello dear experts in php and mysql. Share your experience.
I am making a router for my CMS (with one index.php entry point), described such a method for receiving and parsing url requests from users:

// Прием и разбор запросов
  public function accept()
  {
    $url_el = array();
    $url = $_SERVER['REQUEST_URI'];
    
    if(preg_match("/[^a-zA-Z0-9\/\-\?\=\.\&\#]|(\?{2,}|\-{2,}|\/{2,}|\={2,})/" , $url))
      return false;
        
    $url = parse_url($url);
    $url_el['path'] = $url['path'];
    
    if(!empty($url['path']) && $url['path'] != '/')
    {
      if(preg_match("/^\/([a-z0-9\-]+)\.html$/", $url['path'], $ress))
        $url_el['static'] = end($ress);
      elseif(preg_match("/^\/([a-z0-9\-]+)\/$/", $url['path'], $ress))
        $url_el['category'] = end($ress);
      elseif(preg_match("/^\/([a-z0-9\-]+)\/([a-z0-9\-]+)\/$/", $url['path'], $ress))
      {
        $url_el['category'] = $ress[1];
        $url_el['subcategory'] = end($ress);
      }
      elseif(preg_match("/^\/([a-z0-9\-]+)\/([a-z0-9\-]+)\.html$/", $url['path'], $ress))
      {
        $url_el['category'] = $ress[1];
        $url_el['page'] = end($ress);
      }
      elseif(preg_match("/^\/([a-z0-9\-]+)\/([a-z0-9\-]+)\/([a-z0-9\-]+)\.html$/", $url['path'], $ress))
      {
        $url_el['category'] = $ress[1];
        $url_el['subcategory'] = $ress[2];
        $url_el['page'] = end($ress);
      } 
      else
        return false;
    }

    return $url_el;
  }

Question-1: I'm not very good with regular expressions, is there another way to shorten this method in one line?
Further, the data from the $url_el array will be compared and checked from the data of the categories and publications (pages) database tables, and if all Ok such an address exists in the database, then the router connects the appropriate module (class) for further processing and displaying information for the requested url address.
Question-2: Do you think this approach will not heavily load the database if the site traffic is high (to reduce such a load, it is planned to create caching in the future). Might be worth creating a temporary tableWhere will url-address elements from regular category and page tables be included in the database? But not all hosters support temporary tables.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex, 2015-11-27
@mr_ko

Isn't it easier not to fence bicycles and take some kind of ready-made library? For example https://github.com/nikic/FastRoute

P
Platton, 2015-11-27
@Platton

Dear forum users, I consciously write my bike, I have my own reasons for this. I would like to know your answers to the questions posed. Thank you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question