如何打印当前URL路径?

2022-08-30 13:56:02

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

我在我的文件中使用它.php

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

当我打开网址 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扩展名。

任何人都可以/想帮助我吗?:)


答案 1

你需要而不是,cos将始终给你目前正在工作的文件。$_SERVER['REQUEST_URI']$_SERVER['SCRIPT_NAME']$_SERVER['SCRIPT_NAME']

从手册:

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

我想这有助于您完全获取当前URL。

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

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

安全警告

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

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

因此,在使用用户输入之前,请始终对其进行筛选。至少使用 、 等。htmlspecialcharshtmlentitiesstrip_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']));
}

答案 2
$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'], '/'). '/';
}

推荐