【问题标题】:Database output prevent images数据库输出阻止图像
【发布时间】:2016-04-04 09:16:22
【问题描述】:

有没有办法防止从数据库表中输出 img 元素?

在我的数据库中存储了一些 HTML 代码:

表:test_table
字段:代码

<p>This is simple test!</p><img src="files/test.img">

现在我正在输出数据库内容:

$code = $db->getValue('code');

<?php echo $code ?>

输出code字段的完整内容。我想阻止&lt;img&gt;-element 的输出。

【问题讨论】:

    标签: php jquery mysql database


    【解决方案1】:

    您可以通过两种方式进行操作。首先是其他人建议preg_replace() 或其次使用strip_tags()allowable_tags 参数,您可以在其中定义允许的标签。如果您的输出包含您不想回显的其他标签,那么您是安全的。

    文档示例:

    <?php
    $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
    echo strip_tags($text);
    echo "\n";
    
    // Allow <p> and <a>
    echo strip_tags($text, '<p><a>');
    

    上面的例子会输出:

    Test paragraph. Other text
    <p>Test paragraph.</p> <a href="#fragment">Other text</a>
    

    【讨论】:

    • strip_tags() 是去这里的方式。它比preg_match() 更安全。永远不要使用正则表达式解析 HTML。
    • 工作正常!谢谢你,托马斯!
    【解决方案2】:

    您可以使用 css 来做到这一点。

    <div id="content">
    $code = $db->getValue('code');
    
    <?php echo $code ?>
    </div>
    

    CSS

    #content img{display:none;}
    

    jQuery

    $(function(){
       $('#content img').remove();
    });
    

    【讨论】:

      【解决方案3】:

      您可能需要使用 preg_replace 通过使用 this ,它会将字符串中的所有 &lt;img&gt; 替换为 space

      如果你想替换成其他东西,修改$replaceWith

       $content = '<p>This is simple test!</p><img src="files/test.img"><img src="files/test.img">';
          $replaceWith = " "; 
          $content = preg_replace("/<img[^>]+\>/i", $replaceWith, $content); 
          echo $content;
      

      Example Demo

      与您的代码一起使用:

      $code = $db->getValue('code');
      $content = preg_replace("/<img[^>]+\>/i", " ", $code); 
      echo $content;
      

      【讨论】:

      • 这就是你的理由:3v4l.org/gS9MX - 永远不应该使用正则表达式来解析 HTML。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多