Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Created February 2, 2011 00:36
Show Gist options
  • Save dhrrgn/807021 to your computer and use it in GitHub Desktop.
Save dhrrgn/807021 to your computer and use it in GitHub Desktop.
Get URI
<?php
/**
* Get's the current "pretty" URI from the URL. It will also correct the QUERY_STRING server var and the $_GET array.
* It supports all forms of mod_rewrite and the following forms of URL:
*
* http://example.com/index.php/foo (returns '/foo')
* http://example.com/index.php?/foo (returns '/foo')
* http://example.com/index.php/foo?baz=bar (returns '/foo')
* http://example.com/index.php?/foo?baz=bar (returns '/foo')
*
* Similarly using mod_rewrite to remove index.php:
* http://example.com/foo (returns '/foo')
* http://example.com/foo?baz=bar (returns '/foo')
*
* @author Dan Horrigan <http://dhorrigan.com>
* @copyright Dan Horrigan
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
* @param bool $prefix_slash whether to return the uri with a '/' in front
* @return string the uri
*/
function get_uri($prefix_slash = true)
{
if (isset($_SERVER['PATH_INFO']))
{
$uri = $_SERVER['PATH_INFO'];
}
elseif (isset($_SERVER['REQUEST_URI']))
{
$uri = $_SERVER['REQUEST_URI'];
if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
{
$uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
}
elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
{
$uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
}
// This section ensures that even on servers that require the URI to be in the query string a correct
// URI is found, and also fixes the QUERY_STRING server var and $_GET array.
if (strncmp($uri, '?/', 2) === 0)
{
$uri = substr($uri, 2);
}
$parts = preg_split('#\?#i', $uri, 2);
$uri = $parts[0];
if (isset($parts[1]))
{
$_SERVER['QUERY_STRING'] = $parts[1];
parse_str($_SERVER['QUERY_STRING'], $_GET);
}
else
{
$_SERVER['QUERY_STRING'] = '';
$_GET = array();
}
$uri = parse_url($uri, PHP_URL_PATH);
}
else
{
// Couldn't determine the URI, so just return false
return false;
}
// Do some final cleaning of the URI and return it
return ($prefix_slash ? '/' : '').str_replace(array('//', '../'), '/', trim($uri, '/'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment