Suppose there is site.com , where urls are used for documents /news , /main , /qeqqe
When registering, the user has his own id , and url on his profile /user1
The user has the opportunity to choose your address, for example /doofy instead of /user1

I suppose you can organize this through a redirect with a 404 error, but how to check the existing pages and how to store all the occupied addresses?

According to what scheme does the same ru.stackoverflow.com/users/186999 work , when it opens the profile by user id 186999 ? For example, I got something like that. I do not know how much all this is correct and whether I am going in that direction.

httpd.conf
ErrorDocument 404 /url.php

url.php

 $uri = substr($_SERVER['REQUEST_URI'], 1, 32); if($uri != 'doofy') { header('HTTP/1.1 200 OK', true, 200); $user = $uri; require_once('user.php'); } else { header('HTTP/1.1 404 Not Found', true, 404); require_once('404.php'); } 

The user wanted to use his site.com/shit address, but suddenly the shit folder will be created. How to check it?

  • It is better to parse the query using preg_match, put the results of the parsing into $ _GET and work with it according to the standard scheme. - ilyaplot
  • @ilyaplot, I need a detailed answer, examples of why regular programs are better, options, how simpler, etc. - Mr. Black
  • @ilyaplot You can't put anything in $_GET yourself, then its meaning is lost, you can get out of the bugs, I sent it ?test=mytest and in php I received $_GET['test'] => don't my test - Naumov
  • @Naumov I used the logic of the Yii 1.x framework. Now you are saying that you can't do this for the entire Yii community. - ilyaplot
  • Yokarny babay. What, no one could write to me 2 years ago that this is routing? Hmm, some crutches - Mr. Black

2 answers 2

there is a table for example user_rewrite_uri in mysql

 | entity_id |user_id|user_url_key | ------------ ------------------- | 1 | 11 | myName.html | ------------- ------------------- | 2 | 12 | ohterName.html | ----------- --------------------- 

All requests go to index.php or any router where we simply take the key in our case example.ru/user/myName.html that matches $key = 'myName.html' select it from the table. and we get the id in this case 11 and convert the request to something similar to example.ru/user/id/11 and then render. 404 error should be after all when nothing is found for not straightforward logic will confuse further. It is easier to perceive such a scheme url -> user key || id -> render || 404 url -> user key || id -> render || 404 url -> user key || id -> render || 404 and not url -> id -> 404 -> user key -> render || 404 url -> id -> 404 -> user key -> render || 404 in the latter case is really harder to catch 404 error.

update for concretization I will give an example of routing in my small personal project, you can see here https://github.com/lnroma/ncms/ completely .

  /** * run application * @return bool */ static public function runApplet() { self::dispathEvent('run_application_before',array()); // это эвент для обсервера не обращаем внимания $params = self::getParams(); // берём параметра из url смотри ниже // алгоритм компиляции и проверки config'ов модулей self::$_controllObject = self::loadController($configModul,$params); self::dispathEvent('run_application_after',array()); return true; } 

then take the parameters

 /** * get params request * @return array */ static public function getParams() { $result = array(); $baseUri = parse_url(self::getBaseUrl()); $requestUri = $_SERVER['REQUEST_URI']; if(isset($baseUri['path']) && $baseUri['path'] != '/') { $requestUri = str_replace($baseUri['path'],'',$requestUri); } $params = explode('/',trim($requestUri,'/')); // тут был алгоритм генерации имени модуля, контроллера, action // generate params // $i=3 так как ранее первые 3 параметра это соответственно модуль, контроллер и action for ( $i=3; $i<count($params); $i++ ) { if( $i%2 != 0 ) { if(isset($params[$i+1])) { $result[$params[$i]] = $params[$i+1]; } } } // $result это array вида 'param' => '1', 'param2' => 2 и т.д. return $result; } 

Next comes the controller instance

 /** * call controller action * @param $objectController * @param $params * @return mixed * @throws Exception_Notfound */ static protected function _callControllerAction($objectController,$params) { $params = Core_App::getParams(); $action = $params['action'].'Action'; if(!method_exists($objectController,$action)) { throw new Exception_Notfound('Page not found'); } call_user_func(array($objectController,$action)); return $objectController; } 

Next comes the execution of the requested action in which the array of parameters will actually be available.

Core::app()->getParams()['userKey']; then we already implement a sample with a base, I have them 2-ve mongo and mysql , since I must have the integrity defined for the url I use mysql . The application has a functional on alisam for pages and modules. The mechanism to madness is simple. And it is built mainly on the observatory modules.

  'router_load' => array( 'observer' => 'Pages_Model_Observer', 'method' => array( 'aliasForPage', 'aliasMenu' ) ), 

This is a piece of the module aliasForPage It says that after loading the router, run the aliasForPage and aliasMenu in the Pages_Model_Observer class and Pages_Model_Observer aliasForPage ;

  /** * router for page * @param $data * @return array */ public function aliasForPage($data) { /** @var Driver\Manager $connect */ $connect = Core_Model_Mongo::getConnect(); $man = new MongoDB\Driver\Query( array( 'key' => $this->_getPath() ) ); $collection = $connect->executeQuery(Config_Db::getConf()['mongodb']['db'] . '.pages', $man); if (count($collection->toArray())) { $data = array( 'controller' => 'pages', 'controllerName' => 'view', 'action' => 'index', 'id' => $this->_getPath() ); } return $data; } 

In fact, the method checks whether this url is in byte, if not, then we send the algorithm to run further, if there is, then we say that it should start the next module, with the id parameter, it indicates hash Mongo db. After that, the controller that already generates the page views is started based on the data obtained by means of id.

  • Something is not clear how to get the key , in which document, under what circumstances, through $_SERVER['REQUEST_URI'] ? Why do I need entity_id if I can get the user id by url_key on the same line in the table? - Mr. Black
  • @Doofy entity_id for more convenient administrative actions, deletion, modification, etc. you can not use. - Naumov
  • Ie, what is called routing and is used in such cases, and I guessed with my example by sending the header 200 or 404? By the way in vk really the same thing? How then to check the existing real pages? - Mr. Black
  • you render (generate) the page, do not just display the php or html file. - Naumov
  • After all, the page is generated from the php document template via require_once('user.php'); - Mr. Black

I will give an example of the implementation of routing

 function error404() { header('HTTP/1.1 404 Not Found', true, 404); require_once('404.php'); exit(); } if (empty($_GET['user']) && !preg_match("#^/users/(?P<user>\w+)#u", $_SERVER['REQUEST_URI'], $matches)) { error404(); } foreach ($matches as $param => $value) { if (is_numeric($param)) { continue; } $_GET[$param] = $value; } // Допустим, феункция getUser($user) получает профиль пользователя по username. Если вернет false, значит, юзера не существует. if ($user=getUser($_GET['user'])===false) { error404(); } // Ошибок нет, работаем с профилем пользователя ($user) 
  • It is better to apply the principles of op and not to rewrite the array $_GET . - Naumov
  • @Naumov, I think $_GET is out of place here. The link should look like site.com/doofy , not site.com?user=doofy or site.com/users/doofy - Mr. Black
  • preg_match should be executed if $ _GET ['user'] is empty, and then just work with $ _GET. Corrected the answer taking into account this moment. If you access the script at /users/doofy , we get $ _GET ['user'] = doofy, in the same way as if you go to ?user=doofy - ilyaplot
  • @Naumov I do not see the need for OOP in this particular example. It is possible that the scripts will acquire logic in the future, but OOP needs to be understood. For this question, OOP can only complicate the understanding of the answer. - ilyaplot
  • When /users/doofy error 404 comes out, this is not the same as what ?user=doofy and you cannot get $_GET['user'] - Mr. Black