Mario Legenda
Mario Legenda

Reputation: 759

accessing $_GET[] array with url rewriting

I'm building a website for a hair saloon. I got all the time that i need so I i started to build my MVC framework just to better understand MVC. The core of MVC is url rewriting.

RewriteRule ^(.*)/?$ index.php?url=$1 [L]

That would result in this...

www.example.com/register
$_GET['url'] = 'register'

I decided to make the page post/redirect/get pattern. So when I redirect, the url should be something like this...

www.example.com/register/John/Doe/mail

or something similar. That value is entirely in the $_GET['url'] variable. Is there a way to make the url look like this...

www.example.com/register/?name=John&lastName=Doe&[email protected]

which would be accessabile with $_GET['name'], $_GET['lastName'] etc...?

I know that there is an entire uri in the $_SERVER['REQUEST_URI'] variable, but i was wondering is there a cleaner way to get the values?

Upvotes: 3

Views: 182

Answers (2)

Aurelia
Aurelia

Reputation: 1062

You will need to do your own parsing. I'd strongly recommend you use $_SERVER['QUERY_STRING'] instead, that will also enable you to simply omit the url= part.

Alternatively you can setup more Rewrite Rules, but that has its downsides, like no dynamic handling without generating those rules on the fly (which is also impossible with Webservers other than Apache, like nginx)

Upvotes: 2

preinheimer
preinheimer

Reputation: 3722

I would run explode() on the $_SERVER['REQUEST_URI'] which will give you an enumerated array of elements (like array('register', 'John', 'Doe', 'mail);). Use the first element in the array to map the code to your register function, then you can either accept the numerically indexed elements, or write some generic mapping code that will map it over for you.

Writing something generic like:

function mapper($params, $mapping)
{
  $result = array();
  foreach($mapping as $key => $value)
  {
    $result[$value] = $params[$key];
  }
}

mapper($explodeData, array('function', 'fname', 'lname', 'request');

Then you can handle generic mappings for different functions as your codebase expands.

Upvotes: 2

Related Questions