Get Just The Path from a Request in PHP

It can be a little tricky to get just the path of a request in PHP. $_SERVER['REQUEST_URI'] includes the query string. $_SERVER['SCRIPT_NAME'] may return index.php instead of the request if you’re using a CMS like WordPress which rewrites URLs.

The most reliable method I’ve found for returning only the path without the query string uses PHP’s built in parse_url() function:

$path_only = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);