如何打印当前的URL路径?

时间:2013-02-16 17:16:28

标签: php url

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

我在file.php中使用它

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

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

但是,如果我删除.php扩展程序,以便网址将 http://sub.mydomain.com/file ,则会打印"http://sub.mydomain.com/sub/file.php",这是错误的。

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

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

任何能够/想要帮助我的人都可以吗? :)

2 个答案:

答案 0 :(得分:66)

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

来自手册:

  

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

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

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

注意:不要依赖客户HTTP_HOST,使用SERVER_NAME INSTEAD!见:What is the difference between HTTP_HOST and SERVER_NAME in PHP?

安全警告

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

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

因此,在使用之前始终过滤用户输入。至少使用htmlspecialcharshtmlentitiesstrip_tags等。

或类似的东西;

function get_current_url($strip = true) {
    // 'cos function could be used many times
    static $filter, $scheme, $host;
    if ($filter == null) {
        // sanitizer
        $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;
        };

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

    return sprintf('%s://%s%s', $scheme, $host, $filter($_SERVER['REQUEST_URI']));
}

答案 1 :(得分: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'], '/'). '/';
}