許多開發者都遇過網站檔案被植入惡意代碼的情況,PHP、ASP、HTML、JS 等檔案常在不知不覺中被插入木馬連結。本文提供一個實用的 PHP 類別 clear_virus,能自動掃描並清除受感染的檔案,省去人工逐一檢查的繁瑣工作。
該類別運作流程如下:
virus.txt)e.php)是否含有惡意代碼save.txt)time.txt<?php
class clear_virus {
public $infectFile = 'virus.txt'; // 病毒特徵碼列表
public $savefile = 'save.txt'; // 待掃描檔案清單
public $timep = 'time.txt'; // 清除時間記錄
public $checkFile = 'e.php'; // 偵測觸發檔案
public $run = 0;
public $virus_type = [];
public $replace = '';
public $filepath = [];
public $tag = 0;
public function open_file() {
$this->read_virus();
$this->check_File();
if ($this->run) {
$this->update_time();
$this->read_file();
foreach ($this->filepath as $tmppath) {
if (file_exists($tmppath)) {
$tmp_file = file_get_contents($tmppath);
for ($i = 0; $i < count($this->virus_type); $i++) {
if (strpos($tmp_file, $this->virus_type[$i]) !== false) {
$tmp_file = str_replace($this->virus_type[$i], '', $tmp_file);
$this->tag = 1;
}
}
if ($this->tag) {
file_put_contents($tmppath, $tmp_file);
unset($tmp_file);
}
}
}
}
}
private function check_File() {
if (file_exists($this->checkFile)) {
$temp = file_get_contents($this->checkFile);
foreach ($this->virus_type as $v_tmp) {
if (strpos($temp, $v_tmp) !== false) {
$this->run = 1;
break;
}
}
} else {
$this->show_error(5);
}
}
private function update_time() {
if (file_exists($this->timep)) {
$tmp_time = date("Y-m-d H:i:s") . "\r\n";
file_put_contents($this->timep, $tmp_time, FILE_APPEND);
}
}
private function read_file() {
if (file_exists($this->savefile)) {
$this->filepath = file($this->savefile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
$this->show_error(4);
}
}
private function read_virus() {
if (file_exists($this->infectFile)) {
$this->virus_type = file($this->infectFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
$this->show_error(2);
}
}
private function show_error($number) {
$errors = [
1 => '病毒特徵碼檔案無法讀取!',
2 => '病毒特徵碼列表檔案不存在!',
3 => '檔案清單格式錯誤',
4 => '待掃描檔案清單不存在',
5 => $this->checkFile . ' 不存在,請設定觸發檢測的檔案'
];
echo $errors[$number] ?? '未知錯誤';
}
}
$virus = new clear_virus();
$virus->open_file();
?>
virus.txt,每行一個惡意代碼特徵字串save.txt 列出需掃描的檔案路徑(每行一個)e.php(可包含常被感染的代碼片段)