By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

PHP REQUEST_URI

Reference on the PHP REQUEST_URI Server Variable, and useful examples.

Created: 2012-08-23 13:49

The PHP REQUEST_URI Server Variable is a part of the $_SERVER array, it contains the requested URI such as /index.php without the domain it self.

It can in some situations be useful to check the request uri of the resource, one of such situations is when you do not want your front page to also be accessible on its filename, I.e. /index.php – how to avoid this is shown in the examples.

You can also use the requested uri in your error pages, to find similar pages to what was requested, and to inform the user what was requested.

PHP REQUEST_URI Examples

The below example will output the requested uri in the browser using echo.

echo $_SERVER['REQUEST_URI'];

Below is an example of how to redirect your /index.php to the root / if requested, ideally the front page should only be accessible on the root, and not on a subpage – to avoid this problem, we can check the REQUEST_URI, and perform a redirect if it matches the filename of the front page.

if ($_SERVER['REQUEST_URI'] == '/index.php') {
  header("HTTP/1.1 301 Moved Permanently");
  header('Location: http://brugbart.com/');
  exit();
}