关于html实体转义保存到数据库后出错的问题

      在开发建站程序的过程中,遇到了在后台编辑文章,文章中有html实体,保存到数据库后,第一次打开能正常显示,第二次打开就消失了。这种情况着实令我头疼了好长一段时间,而经过昨天到今天的努力,不断查资料,不断测试,总算搞清楚这个问题了。同时也想明白了,为什么自己当初写代码,$Article->get($aid)和$Article->get_one($aid)这种获取一篇文章的方法要写两个,前台用一个,后台用一个。

      具体怎么解释其中的缘由,因为复杂,还需要慢慢理清思路,现在只说解决方案。

      文章正文的变量是$content,在后台编辑文章保存的时候,给$content变量使用 htmlspecialchars() 函数,确保数据进入数据库的时候$content里面的html标签是经过转义的。然后从数据库取出文章的时候,如果是用于后台,直接使用$congtent,如果是用于前台显示,就要给$content进行反转义,即 $content=htmlspecialchars_decode($content)。这样子在后台看到的是源代码,在前台看到的是想要的样子。

      后台保存文章时的代码

$title = addslashes(getPost('title'));
$content = addslashes(htmlspecialchars(getPost('content')));//对正文进行转义
$keywords = addslashes(tagdispose(getPost('keywords')));
$description = addslashes(getPost('description'));
...
$post['title'] = $title;
$post['content'] = $content;
$post['keywords'] = $keywords;
$post['description'] = $description ? $description : addslashes(html_extract_txt($description, 150));
...
$aid = $Post_Model->add($post);

      在模型中获取数据时的代码

function get($aid, $admin=false) {
    #$admin 是否在后台使用,需要对正文编辑时 $admin为真
    $sql = "SELECT * FROM " . DB_PREF . SYS . "_post WHERE aid=$aid";
    $row = $this->db->fetch_one($sql);
    if ($row) {
        $row['title'] = $admin ? $row['title'] : $row['title'];
        $row['keywords'] = $admin ? $row['keywords'] : htmlspecialchars_decode($row['keywords']);
        $row['description'] = $admin ? $row['description'] : htmlspecialchars_decode($row['description']);
        $row['content'] = $admin ? $row['content']  : htmlspecialchars_decode($row['content']);
        #三元表达式 = $admin为真,就不用对数据修改,否则进行反转义。
        ...
       return $row;
    } else {
        return false;
    }
}
标签:php html实体
分类:编程笔记 时间:2021年05月09日 浏览:274