酷秀  - kxiu.cn

typecho实现多个文章部分内容加密教程

admin的头像admin5个月前教程102热度

需求说明

typecho文章虽然自带了加密功能,可是有时候不太人性化,例如我想要显示部分内容,部分内容加密而且多个部分加密的密码不同。

多个部分内容加密截图

图片

提交密码查看效果截图

图片

这篇文章就是为了解决上面提供的方案思路,具体各项细节需要开发者自行在进一步完善(例如添加cookie,session等缓存提交的密码实现在一定时间内不用重复输入等,下面的代码为了理解就没有添加)。

具体实现代码

把下面的代码添加到“post.php”文件中即可(重要提示:需要把下面的代码加到“$this->content”之前),当然还有通过其他方法也可以实现,这里为了方便就简单粗暴。

if ($this->request->isPost() && $this->request->mm === 'ok'){

  if (strpos($this->content, '{mm') !== false) {

    $this->content = preg_replace_callback('/{mm id="(.+?)"}(.+?){\/mm}/',function($match){
      if ($this->request->pass === $match[1]){
        return $match[2];
      }else{
        return $match[0];
      }
    }, $this->content);

  }
}

if (strpos($this->content, '{mm') !== false) {

  $this->content = preg_replace('/{mm id="(.+?)"}(.+?){\/mm}/',"<form action='?mm=ok' class='xm-mm' id='xm-mm' method='post'>
    <div class='xm-mm-input' id='xm-mm-input'>
      <input type='password' class='xm-mm-pass' id='xm-mm-pass' name='pass' placeholder='请输入密码'>
    </div>
    <div class='xm-mm-button' id='xm-mm-button'>
      <button type='submit' class='xm-mm-submit' id='xm-mm-submit'>提交</button>
    </div>
</form>", $this->content);
}

在写文章的时候,部分内容需要加密的内容用如下代码即可

{mm id="这里填写密码"}这里是要加密的文章内容{/mm}
签名: 最忠诚的BUG开发者来自: 重庆市. Chrome浏览器
文章目录

新年快乐

×
新年快乐
同喜