【发布时间】:2019-03-07 20:01:05
【问题描述】:
我正在为网站使用 wordpress。我正在使用 sn-ps(我自己的自定义 php 代码)从数据库中获取数据并将该数据回显到我的网站上。
if($_GET['commentID'] && is_numeric($_GET['commentID'])){
$comment_id=$_GET['commentID'];
$sql="SELECT comments FROM database WHERE commentID=$comment_id";
$result=$database->get_results($sql);
echo "<dl><dt>Comments:</dt>";
foreach($result as $item):
echo "<dd>".$item->comment."</dd>";
endforeach;
echo "</dl>";
}
此特定页面从 URL 中读取一个 ID,并显示与该 ID 相关的所有 cmets。在大多数情况下,这些 cmets 是文本。但是一些 cmets 应该能够指向我网站上的其他页面。
例如,我希望能够在数据库中的评论字段中输入:
This is a magnificent comment. You should also check out <a href=\"<?php getURLtoSectionPage($commentID) ?>\">this other section</a> for more information
其中 getURLtoSectionPage() 是我在 functions.php 中声明的一个函数,用于为主页的每个部分提供静态 URL,以防止在将来更改我的 URL 模式时链接断开。
我不想通过使用 eval() 来执行此操作,并且我也无法通过使用输出缓冲区来完成此操作。我将不胜感激有关如何尽可能安全和干净地完成这项工作的任何提示。我不希望执行任何自定义 php 代码,只对我现有的验证输入参数的函数进行函数调用。
更新: 感谢您的回复。这个问题我想了很久,花了一晚上的时间试验,想出了如下解决方案。
我的 SQL “简码”:
This is a magnificent comment. You should also check out <a href=\"[custom_func:getURLtoSectionPage:42]\">this other section</a> for more information
我在 wordpress 中的 php sn-p:
ob_start();
// All my code that echo content to my page comes here
// Retrieve ID from url
// Echo all page contents
// Finished generating page contents
$entire_page=ob_get_clean();
replaceInternalLinks($entire_page);
wordpress 中我的functions.php 中的PHP 函数
if(!function_exists("replaceInternalLinks")){
function replaceInternalLinks($reference){
mb_ereg_search_init($reference,"\[custom_func:([^\]]*):([^\]]*)\]");
if(mb_ereg_search()){
$matches = mb_ereg_search_getregs(); //get first result
do{
if($matches[1]=="getURLtoSectionPage" && is_numeric($matches[2])){
$reference=str_replace($matches[0],getURLtoSectionPage($matches[2]),$reference);
}else{
echo "Help! An unvalid function has been inserted into my tables. Have I been hacked?";
}
$matches = mb_ereg_search_regs();//get next result
}while($matches);
}
echo $reference;
}
}
这样我可以决定哪些函数可以通过简码格式调用,并且可以验证只能使用整数引用。
我现在安全了吗?
【问题讨论】:
-
危险:你很容易受到SQL injection attacks的影响,你需要defend你自己。
-
使用一些代码,比如
[func:getURLtoSectionPage:commentId],而不是为允许的函数和参数使用一些白名单并在php中调用函数... -
在纯 PHP 中,您应该为此发明自己的有限标记,例如
foo [url:comment:42] bar或类似的东西。这可以安全地替换为preg_replace_callback('/\[url:(\w+):(\d+)\]/', ...)之类的东西。在 Wordpress 中,我没有真正的想法,但你也许可以使用短代码之类的东西。 -
我之前考虑过使用简码,但决定反对它,因为我希望能够在我的任何表格、任何单元格中插入自定义链接,并让它们动态解析为正确的页面。例如,我希望能够根据我调用的函数重定向链接。这样我就可以在更改内容时更新我的函数,而不是更新所有 cmets。但我认为我已经通过将您的提示与输出缓冲结合起来解决了这个问题,这让我可以使用短代码在任何地方动态替换内部链接。您认为更新后的解决方案可以安全使用吗?