Akismet 是廣泛使用的反垃圾服務,需 API Key。本文展示整合類別與表單處理流程。
<?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>
參考 Script Tutorials 範例改寫。