Search code examples
php.htaccessuriurl-routingpsr-7

How to read the request URI?


For my own MVC I need to read the request URI from the global variables ($_GET or $_SERVER).

First I thought to read it from $_GET array. But then I discovered that it's contained in the $_SERVER array as well.

So, I would like to ask, from which global array should the request URI be read?


An example:

The URI could have the following structure:

http://local.mvc/PsrTest/testRequest/123?var=someval

with:

  • PsrTest as controller name;
  • testRequest as action name;
  • 123 as argument for the controller action;
  • var=someval as some query string key/value pair;

By applying a RewriteRule in ".htaccess", it will be translated to:

http://local.mvc/index.php?url=PsrTest/testRequest/123&var=someval

and it will be saved in the following items of the $_GET and $_SERVER arrays:

------------
$_GET array:
------------

'url' => 'PsrTest/testRequest/123'
'var' => 'someval'

---------------
$_SERVER array:
---------------

'HTTP_REFERER' => 'http://local.mvc/PsrTest/testRequest/123?var=someval'
'REDIRECT_QUERY_STRING' => 'url=PsrTest%2ftestRequest%2f123&var=someval'
'REDIRECT_URL' => '/PsrTest/testRequest/123'
'QUERY_STRING' => 'url=PsrTest%2ftestRequest%2f123&var=someval'
'REQUEST_URI' => '/PsrTest/testRequest/123?var=someval'

Thank you for your time!


Solution

  • As @teresko suggested, .htaccess are not always a possibility. Then it makes indeed no more sense (at least for me) to write RewriteRules in .htaccess, which translate the given URI into query string parameters. It will be sufficient to:

    • Just write a simple rule, like RewriteRule ^ index.php [L] in .htaccess;
    • Just parse the $_SERVER['REQUEST_URI'] value in PHP, in order to get the URI components needed to call a controller action and to pass the corresponding parameters to it.

    I'm grateful to all the users who helped me finding my answer. Thanks!