Trying to get a full URL without filename in PHP

Viewed 50902

I thought this would be simple but I can't seem to find a variable of $_SERVER array that has what I'm looking for.

Let's say my url is http://example.com/subdirectory/index.php I want to get all but the filename - http://example.com/subdirectory/.

I know I could quite easily do this with some string manipulation, but I want to know if there's a var of the _server array that I'm just missing. I've tried all of them to see what they give and I can get anything BUT what I'm looking for.

7 Answers

This worked perfectly for me and seems to be a very clean solution.

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$path = $protocol.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);

Another solution, without dirname and respecting http and https is to use the old fashioned get path method (source from this stackoverflow answer). Then check if the path ends with the fileextension ".php". If true, remove it from the path.

Long version

$current_url_path = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if (substr($current_url_path, -4) == ".php") {
    // path ends with .php
    // split string to array
    $arr = explode("/", $current_url_path);

    // remove last array item (after the last / which is the file)
    $arrS = array_slice($arr, 0, -1);

    // join the array to a string
    $current_url_path = implode("/", $arrS);
}
echo $current_url_path;

Shortened version

$current_url_path = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$current_url_path = substr($current_url_path, -4) == ".php" ?
    implode("/", array_slice((explode("/", $current_url_path)), 0, -1)) : $current_url_path;

echo $current_url_path;

Test

This url: http://localhost/comp-test/test.php is returned as http://localhost/comp-test

Related