我使用PHP构建当前页面的URL。的形式

www.example.com/myurl.html?unwantedthngs

是要求。我想把?和它后面的所有内容(querystring),这样得到的URL就变成:

www.example.com/myurl.html

我现在的代码是这样的:

<?php
function curPageURL() {
    $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;
}
?>

当前回答

试试这个:

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']

or

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']

其他回答

使用PHP Manual - parse_url()来获取您需要的部分。

编辑(例如@Navi Gamage的用法)

你可以这样使用它:

<?php
function reconstruct_url($url){
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];

    return $constructed_url;
}

?>

编辑(第二个完整示例):

更新功能,确保方案将附加,没有通知msgs出现:

function reconstruct_url($url){
    $url_parts = parse_url($url);
    $constructed_url = $url_parts['scheme'] . '://' . $url_parts['host'] . (isset($url_parts['path'])?$url_parts['path']:'');

    return $constructed_url;
}

$test = array(
    'http://www.example.com/myurl.html?unwan=abc',
    `http://www.example.com/myurl.html`,
    `http://www.example.com`,
    `https://example.com/myurl.html?unwan=abc&ab=1`
);

foreach($test as $url){
    print_r(parse_url($url));
}

将返回:

Array
(
    [scheme] => http
    [host] => www.example.com
    [path] => /myurl.html
    [query] => unwan=abc
)
Array
(
    [scheme] => http
    [host] => www.example.com
    [path] => /myurl.html
)
Array
(
    [scheme] => http
    [host] => www.example.com
)
Array
(
    [path] => example.com/myurl.html
    [query] => unwan=abc&ab=1
)

这是通过不带第二个参数的parse_url()传递示例url的输出(仅供解释)。

这是使用构造URL后的最终输出:

foreach($test as $url){
    echo reconstruct_url($url) . '<br/>';
}

输出:

http://www.example.com/myurl.html
http://www.example.com/myurl.html
http://www.example.com
https://example.com/myurl.html
$val = substr( $url, 0, strrpos( $url, "?"));

试试这个:

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']

or

$urrl=$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']

因为我同时处理相对url和绝对url,所以我更新了veritas的解决方案,如下所示。 你可以在这里试试:https://ideone.com/PvpZ4J

function removeQueryStringFromUrl($url) {
    if (substr($url,0,4) == "http") {
        $urlPartsArray = parse_url($url);
        $outputUrl = $urlPartsArray['scheme'] . '://' . $urlPartsArray['host'] . ( isset($urlPartsArray['path']) ? $urlPartsArray['path'] : '' );
    } else {
        $URLexploded = explode("?", $url, 2);
        $outputUrl = $URLexploded[0];
    }
    return $outputUrl;
}

你可以试试:

<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>