Skip to content

Instantly share code, notes, and snippets.

@Edwin-Luijten
Created March 7, 2012 21:40
Show Gist options
  • Save Edwin-Luijten/1996418 to your computer and use it in GitHub Desktop.
Save Edwin-Luijten/1996418 to your computer and use it in GitHub Desktop.
PHP : Get url segment
/**
*Get url segment
*@param int
*@return string [name of requested url segment]
**/
function getSegment((int)$segmentPart)
{
if(is_int($segmentPart))
{
//Full path
$path = trim($_SERVER['REQUEST_URI'], '/');
//Create array of segments from full path
$segment = explode('/', $path);
//Check if $segment[$segmentPart] is set else it gives undefined offset with no segments in the url
if(isset($segment[$segmentPart]))
{
return $segment[$segmentPart];
}
else
{
throw new Exception('$segment[$segmentPart] not set.');
}
}
else
{
throw new Exception('Parameter must be an integer.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment