33

我想打印出当前的 URL 路径,但我的代码不能正常工作。

我在我的 file.php 中使用它

echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];

当我打开 url http://sub.mydomain.com/file.php它似乎工作正常,它打印"http://sub.mydomain.com/file.php"

但是,如果我删除 .php 扩展名,因此 url 将改为http://sub.mydomain.com/file,它会打印"http://sub.mydomain.com/sub/file.php"出错误的。

它打印子域两次,我不知道为什么?

在我的 .htaccess 文件中,我进行了重写,可以删除 .php 扩展名。

有谁可以/想帮助我吗?:)

4

2 回答 2

68

您需要$_SERVER['REQUEST_URI']而不是$_SERVER['SCRIPT_NAME'],cos$_SERVER['SCRIPT_NAME']将始终为您提供当前正在工作的文件。

从手册:

SCRIPT_NAME:包含当前脚本的路径。这对于需要指向自身的页面很有用。该__FILE__常量包含当前(即包含的)文件的完整路径和文件名。.

我想这可以帮助您完全获取当前 URL。

echo 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];

注意:不要依赖客户的HTTP_HOST,而是使用SERVER_NAME!SEE:PHP 中的 HTTP_HOST 和 SERVER_NAME 有什么区别?

安全警告

如果您在任何地方使用它(打印或存储在数据库中),您需要过滤(清理)$_SERVER['REQUEST_URI'],因为它不安全。

// ie: this could be harmfull
/user?id=123%00%27<script...

因此,请始终在使用用户输入之前对其进行过滤。至少使用htmlspecialchars,htmlentitiesstrip_tags

或类似的东西;

function get_current_url($strip = true) {
    static $filter, $scheme, $host, $port; 
    if ($filter == null) {
        $filter = function($input) use($strip) {
            $input = trim($input);
            if ($input == '/') {
                return $input;
            }

            // add more chars if needed
            $input = str_ireplace(["\0", '%00', "\x0a", '%0a', "\x1a", '%1a'], '',
                rawurldecode($input));

            // remove markup stuff
            if ($strip) {
                $input = strip_tags($input);
            }

            // or any encoding you use instead of utf-8
            $input = htmlspecialchars($input, ENT_QUOTES, 'utf-8');

            return $input;
        };

        $scheme = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME']
            : ('http'. (($_SERVER['SERVER_PORT'] == '443') ? 's' : ''));
        $host = $_SERVER['SERVER_NAME'];
        $port = ($_SERVER['SERVER_PORT'] != '80' && $scheme != 'https')
            ? (':'. $_SERVER['SERVER_PORT']) : '';
        }
    }

    return sprintf('%s://%s%s%s', $scheme, $host, $port, $filter($_SERVER['REQUEST_URI']));
}
于 2013-02-16T17:49:47.937 回答
0
$main_folder = str_replace('\\','/',dirname(__FILE__) );
$document_root = str_replace('\\','/',$_SERVER['DOCUMENT_ROOT'] );
$main_folder = str_replace( $document_root, '', $main_folder);
if( $main_folder ) {
    $current_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME']. '/' . ltrim( $main_folder, '/' ) . '/';
} else {
    $current_url = $_SERVER['REQUEST_SCHEME'].'://'.rtrim( $_SERVER['SERVER_NAME'], '/'). '/';
}
于 2017-03-19T18:52:26.987 回答