php 如何在PHP中获取当前页面的URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1283327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:52:27  来源:igfitidea点击:

How to get URL of current page in PHP

php

提问by Click Upvote

In PHP, how can I get the URL of the current page? Preferably just the parts after http://domain.com.

在 PHP 中,如何获取当前页面的 URL?最好是http://domain.com之后的部分。

回答by Amber

$_SERVER['REQUEST_URI']

For more details on what info is available in the $_SERVER array, see the PHP manual page for it.

有关 $_SERVER 数组中可用信息的更多详细信息,请参阅PHP 手册页

If you also need the query string (the bit after the ?in a URL), that part is in this variable:

如果您还需要查询字符串(?URL 中的后面的位),则该部分在此变量中:

$_SERVER['QUERY_STRING']

回答by Jonas Orrico

if you want just the parts of url after http://domain.com, try this:

如果您只想要http://domain.com之后的 url 部分,请尝试以下操作:

<?php echo $_SERVER['REQUEST_URI']; ?>

if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.

如果当前 url 是http://domain.com/some-slug/some-id,echo 将只返回 '/some-slug/some-id'。

if you want the full url, try this:

如果你想要完整的网址,试试这个:

<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

回答by Tyler Carter

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

这将为您提供请求的目录和文件名。如果您使用 mod_rewrite,这将非常有用,因为它会告诉您用户正在查看的页面。

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

如果您需要实际的文件名,您可能想要尝试$_SERVER['PHP_SELF']魔术常量__FILE__$_SERVER['SCRIPT_FILENAME']。后两个为您提供完整路径(从服务器的根目录),而不仅仅是您网站的根目录。它们对于包含等很有用。

$_SERVER['PHP_SELF']gives you the file name relative to the root of the website.

$_SERVER['PHP_SELF']为您提供相对于网站根目录的文件名。

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

回答by Imagist

The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ?in a URI, you should use the $_GET[]array.

其他答案都是正确的。但是,请注意:如果您想?在 URI之后获取内容,则应该使用$_GET[]数组。

回答by user2862106

You can use $_SERVER['HTTP_REFERER']this will give you whole URL for example:

您可以使用$_SERVER['HTTP_REFERER']它为您提供完整的 URL,例如:

suppose you want to get url of site name www.example.comthen $_SERVER['HTTP_REFERER']will give you https://www.example.com

假设您想获取网站名称的网址,www.example.com然后$_SERVER['HTTP_REFERER']会给您https://www.example.com