如何link到当前PHP文件
How to link to the current PHP file
我正在写一个 PHP 文件,但我不知道创建 link 的最佳方法是什么,而 link 在同一个文件中但不同ID。我的意思是我有一个名为 test.php
的文件,它包含类似以下内容的内容:
if ($id == "") {
echo "<a href='".$_SERVER['PHP_SELF']."?id=test'>Try the test page</a>";
} else if ($id == "test") {
echo "Here is the testing content with various information!";
}
我想知道什么是更安全的代码:
$_SERVER['PHP_SELF']?id=test
或 test.php?id=test
.
我知道它现在的用途相同,但如果我更改文件名 $_SERVER['PHP_SELF']?id=test
似乎更好,因为它仍会指向同一个文件。
但我想确定哪个更安全。
你不应该打印 $_SERVER['PHP_SELF']
;这是一个安全漏洞(这里有一个例子:How To Identify The Requested Page In PHP)。
如果您尝试 link 到同一页面,但使用查询参数 (?
) 或锚点 (#
),您可以直接 link对他们来说,正如@kingkero 所建议的那样。
<!--
The code snippet runs as an iframe from http://stacksnippets.net/js,
so that's the root of the links you'll see if you click "Run".
-->
<a href="">Link to current page</a><br />
<a href="?id=test">Add query param to current page</a><br />
<a href="#anchor">Add anchor tag to current page</a>
不以 /
或协议(如 http://
)开头的链接是相对于当前文档位置的。以 /
开头的链接是相对于域根目录的。 W3C.
规定了行为
从广义上讲,你是对的,你应该避免将文件名之类的东西硬编码到你的文件中。但是您通常也不需要使用 $_SERVER
中的数据来构造 links.
我正在写一个 PHP 文件,但我不知道创建 link 的最佳方法是什么,而 link 在同一个文件中但不同ID。我的意思是我有一个名为 test.php
的文件,它包含类似以下内容的内容:
if ($id == "") {
echo "<a href='".$_SERVER['PHP_SELF']."?id=test'>Try the test page</a>";
} else if ($id == "test") {
echo "Here is the testing content with various information!";
}
我想知道什么是更安全的代码:
$_SERVER['PHP_SELF']?id=test
或 test.php?id=test
.
我知道它现在的用途相同,但如果我更改文件名 $_SERVER['PHP_SELF']?id=test
似乎更好,因为它仍会指向同一个文件。
但我想确定哪个更安全。
你不应该打印 $_SERVER['PHP_SELF']
;这是一个安全漏洞(这里有一个例子:How To Identify The Requested Page In PHP)。
如果您尝试 link 到同一页面,但使用查询参数 (?
) 或锚点 (#
),您可以直接 link对他们来说,正如@kingkero 所建议的那样。
<!--
The code snippet runs as an iframe from http://stacksnippets.net/js,
so that's the root of the links you'll see if you click "Run".
-->
<a href="">Link to current page</a><br />
<a href="?id=test">Add query param to current page</a><br />
<a href="#anchor">Add anchor tag to current page</a>
不以 /
或协议(如 http://
)开头的链接是相对于当前文档位置的。以 /
开头的链接是相对于域根目录的。 W3C.
从广义上讲,你是对的,你应该避免将文件名之类的东西硬编码到你的文件中。但是您通常也不需要使用 $_SERVER
中的数据来构造 links.