首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 整合 Akismet 防垃圾留言完整實作

     編輯:PHP 綜合知識

前言

Akismet 是廣泛使用的反垃圾服務,需 API Key。本文展示整合類別與表單處理流程。

核心類別:MySpamProtection

<?php
require_once 'classes/Akismet.class.php';

class MySpamProtection {
    private $apiKey;
    private $blogUrl;
    private $authorName;
    private $authorEmail;
    private $authorUrl;
    private $akismet;

    public function __construct() {
        $this->apiKey = '__YOUR_AKISMET_KEY__';      // 替換為你的 Key
        $this->blogUrl = '__YOUR_WEBSITE_URL__';     // 部落格首頁網址
        $this->authorName = '__YOUR_NAME__';         // 留言者預設名稱
        $this->authorEmail = '';
        $this->authorUrl = '';

        $this->akismet = new Akismet($this->blogUrl, $this->apiKey);
        $this->akismet->setCommentAuthor($this->authorName);
        $this->akismet->setCommentAuthorEmail($this->authorEmail);
        $this->akismet->setCommentAuthorURL($this->authorUrl);
    }

    public function isSpam(string $content): bool {
        if (!$this->akismet) return false;
        $this->akismet->setCommentContent($content);
        return $this->akismet->isCommentSpam();
    }
}

前端表單與處理邏輯

<?php
$protection = new MySpamProtection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $author = $_POST['author'] ?? '';
    $comment = $_POST['comment'] ?? '';

    $authorSpam = $protection->isSpam($author) ? '標記為垃圾' : '正常';
    $commentSpam = $protection->isSpam($comment) ? '標記為垃圾' : '正常';

    echo "作者:$authorSpam
"; echo "留言:$commentSpam
"; } ?> <form method="post"> <div><label>作者</label><input name="author" type="text"></div> <div><label>留言</label><textarea name="comment"></textarea></div> <button type="submit">送出</button> </form>

注意事項

  • 需申請 Akismet API Key(個人免費、商業付費)。
  • 誤判機制:Akismet 非 100% 準確,建議提供「非垃圾」回報機制讓使用者申訴。
  • 效能:API 呼叫需網路往返,考慮非同步處理或快取近期判斷結果。
  • 隱私:傳送留言內容、IP、User-Agent 至第三方,需符合隱私政策說明。

來源

參考 Script Tutorials 範例改寫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved