在配置文件中存储 html 的最佳方法


Best way to store html in a config file

我正在编写自己的下载跟踪器,我想为用户提供在下载页面上显示自定义消息的功能。我想允许 html 和 javascript,这样用户就可以写一个段落或使用广告代码等。

我将我的设置存储在配置文件中(不是我知道的最好的方法)

示例:<?php define("WAIT_MESSAGE", "htmlcodehere"); ?>

问题是引号或斜杠会弄乱配置文件,并且设置页面将无法加载。我已经研究了添加斜杠以尝试转义这些字符,但它只是添加了多个斜杠。

在我的配置文件中存储html内容/javascript的最佳方法是什么?

编辑:尝试了几种方法,但每次我单击保存以更新配置文件"hello"变为"hello"等时,所有这些引号都是转义

不应该相信你的用户,以至于你让他们在你的网站上发布和保存JavaScript和HTML。

允许用户实际将HTML/Javascript/PHP插入到您的页面中是一件非常糟糕的事情

说了这么多,这个问题是一个不时困扰我们所有人的问题。您需要的是将HTML代码以某种不会改变上述代码含义的格式存储。

此问题通常通过将任何此类字符转换为其等效的 HTML 实体来解决,以便您可以安全地存储

查看 http://php.net/manual/en/function.htmlspecialchars.php 和 http://www.php.net/manual/en/function.htmlspecialchars-decode.php 以获取更多信息。

你试过像单曲一样吗?

<?php define('WAIT_MESSAGE', '<p>Please wait.. your download starts shortly</p>'); ?>

这根本不安全。有人可以很容易地将PHP注入其中。

你可以做的(这有点黑客)是base64_encode()数据,并在需要使用时base64_decode()它。这样做将摆脱引号/特殊字符问题和安全问题。

在配置文件中编写base64_encoded HTML 后,要使用它,您将执行以下操作:

<?php
    echo base64_decode(WAIT_MESSAGE);
?>

就个人而言,我会在数据库中保存任何可编辑的值以确保安全,但是,如果您真的想要/需要编辑PHP配置文件,那么这可能是最安全的方法。

<?php 
/*Function to check if magic_quotes is enabled.
 (Stops double slashes happening)
*/
function check_magic_quotes($value){
    if (get_magic_quotes_gpc()) {
        return stripslashes($value);
    } else {
        return $value;
    }
}
/*Form was posted, 
You should also do a check to see if logged in and have rights to edit*/
if($_SERVER['REQUEST_METHOD']=='POST'){
    //Check for magic quotes and then base64_encode the string.
    $value = base64_encode(check_magic_quotes($_POST['configVal']));
    /*Use heredoc to create the php line for the config & insert the
      base64 encoded string into place*/
$config=<<<CONFIG
    <?php define("WAIT_MESSAGE", '$value'); ?>
CONFIG;
    file_put_contents('someConfig.php',$config);
}

//When you want to include the config
include('someConfig.php');
/*To echo out the config value: base64_decode it,
  and then htmlentities encode it, to protect from XSS*/
echo 'This was included: '.htmlentities(base64_decode(WAIT_MESSAGE));

//Basic form with current value when someConfg.php has not been included
$config = file_get_contents('someConfig.php');
preg_match("#'"WAIT_MESSAGE'", '(.*?)'#",$config,$match);
 ?>
<form method="POST" action="">
  <p>Config Value:<input type="text" name="configVal" value="<?php echo htmlentities(base64_decode($match[1]));?>" size="20"><input type="submit" value="Update"></p>
</form>