我使用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;
}
?>

当前回答

要从请求URI中删除查询字符串,请将查询字符串替换为空字符串:

function request_uri_without_query() {
    $result = $_SERVER['REQUEST_URI'];
    $query = $_SERVER['QUERY_STRING'];
    if(!empty($query)) {
        $result = str_replace('?' . $query, '', $result);
    }
    return $result;
}

其他回答

最好的解决办法:

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

如果你正在向同一个域提交表单,则不需要在<form action="">中包含http://example.com。

你可以使用strtok在第一次出现之前获取字符串?

$url = strtok($_SERVER["REQUEST_URI"], '?');

Strtok()代表了直接提取?在查询字符串中。explosion()不太直接,因为它必须生成一个可能包含两个元素的数组,必须通过该数组访问第一个元素。

其他一些技术可能会在查询字符串丢失或url中其他/非预期的子字符串发生变化时中断——这些技术应该避免。

一个示范:

$urls = [
    'www.example.com/myurl.html?unwantedthngs#hastag',
    'www.example.com/myurl.html'
];

foreach ($urls as $url) {
    var_export(['strtok: ', strtok($url, '?')]);
    echo "\n";
    var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
    echo "\n";
    var_export(['explode/2: ', explode('?', $url, 2)[0]]);  // limit allows func to stop searching after first encounter
    echo "\n";
    var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]);  // not reliable; still not with strpos()
    echo "\n---\n";
}

输出:

array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => 'www.example.com/myurl.html',
)
---
array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => false,                       // bad news
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => '',                          // bad news
)
---

试试这个:

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

or

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

你可以试试:

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