PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
So I've been trying to create proper URL rewriting managed by PHP and not in the htaccess.
So far I have this code which works but I'd like to simplify it.
What I mean this:
/news/3/1/
would map to:
/index.php?section=news&id=3&page=1
But for example I'd like to make the order of the query string items irrelevant, in case I have e.g.
/index.php?section=news&page=1&id=3
or simply not to have to define each query string parameter order myself.
This is a very common task that is usually performed by an MVC library. Try a general function for parsing defined routes.
Here is my idea. The `$routes` array has keys that represent the view file to use; it has values that represent the names of the variables to save to $_GET and $_REQUEST.
Example usage: `getViewPath($routes, '/news/3/1');` returns 'views/news.php' and sets `$_GET['id'] = '3'` and `$_GET['page'] = '1'`.
Also, consider making a converse function that takes a view name and an associative array and returns a url. e.g. `url('news', array('id'=>3, 'page'=>1))` would return `"/news/3/1"`. That will reduce chance of error and allow you to change your routing scheme any time.
Are you wanting to continue to do this in PHP, or are you looking for an .htaccess solution?
In order for the order of parameters to not matter, there can be no chance of collision. For example, what if you have a page with an ID 3, and an (I'm guessing article) id of 1? Either the order is significant, which is common practice and not bad at all, or you need to guarantee the separation by coming up with different tokens, ie: /news/page:1/id:3/, or news/p1/i3/ etc.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.