我正在将wordpress用于网站。我正在使用代码片段(我自己的自定义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相关的所有注释。在大多数情况下,这些评论是文本。但是有些评论应该能够指向我网站上的其他页面。
例如,我希望能够输入数据库的注释字段:
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代码段:
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);
我的functions.php中的PHP函数在wordpress中
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;
}
}
这样,我可以决定可以通过短码格式调用哪些函数,并且可以验证只能使用整数引用。
我现在很安全吗?
答案 0 :(得分:0)
不要将代码存储在数据库中,请存储ID,然后在需要时进行处理。顺便说一句,我假设您确实需要它是动态的,并且您不能仅存储最终URL。
因此,我将您的示例注释字段文本更改为:
This is a magnificent comment. You should also check out <a href="#comment-47">this other section</a> for more information
然后,当您需要显示该文本时,对'href="#comment-([0-9]+)"'
进行正则表达式搜索替换,例如 ,此时调用getURLtoSectionPage()
函数 。
这有意义吗?
答案 1 :(得分:0)
我不想使用eval()来做到这一点,而且我也不能通过使用输出缓冲区来做到这一点。对于任何有关如何使它尽可能安全,干净地工作的提示,我将不胜感激。我不希望执行任何自定义的php代码,而仅对已存在的函数进行函数调用以验证输入参数。
Eval是一种可怕的方法,因为它允许人们完全提交原始PHP。它非常容易出错,错误的结果可能是灾难性的(而且甚至没有考虑到恶意攻击者设计的代码可能会被提交)。
您需要使用自定义内容。可能受BBCode启发。