Pregunta

Let's say I have this URL:

http://test.com/directory-test/?id=4746&other=454#comments

How can I retrieve the URL of that specific page with PHP, however, just without all of the variables and #s. So for example:

http://test.com/directory-test/

I found this function, however, it includes EVERYTHING in the URL, so it returns a URL that looks like the first example above, but I want a URL that looks like the second example.

function curPageURLALL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
¿Fue útil?

Solución

Use PHP_SELF instead of REQUEST_URI :)

function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["PHP_SELF"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"];
    }
    return $pageURL;
}

Hymm, PHP_SELF might return also the file example index.php so maybe this

function curPageURL() {
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    $pageURL .= $_SERVER["SERVER_NAME"];
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= ":".$_SERVER["SERVER_PORT"];
    }
    $pos = strpos($_SERVER["REQUEST_URI"],"?");
    $pageURL .= ($pos===false)?$_SERVER["REQUEST_URI"]:substr($_SERVER["REQUEST_URI"],0,$pos);
    return $pageURL;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top