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

PHP 清除網頁惡意腳本病毒的實作方法

     編輯:PHP 綜合知識

網頁被植入惡意腳本(如 <script src="https://ave3.cn></script>)是常見的安全問題。這類病毒通常透過檔案寫入漏洞注入靜態頁面,導致訪客瀏覽時載入外部惡意程式碼。本文提供一個 PHP 類別範例,示範如何掃描並清除指定檔案中的已知病毒特徵碼。

核心思路

透過 file_get_contents() 讀取檔案內容,使用 strpos() 或 strrpos() 檢測是否存在病毒特徵字串,若發現則以 str_replace() 移除後寫回檔案。此為針對已知特徵碼的「事後清除」手段,無法防禦未知變種,實務上仍需配合 WAF、檔案權限控管、定期掃描等防護措施。

程式碼範例

<?php
class ClearVirus {
    public $index = 'b.html';               // 目標檔案
    public $filepath = array('b.html');     // 可擴充為多檔案掃描
    public $virus_type = "<script src=https://%61%76%65%33%2E%63%6E></script>"; // URL 編碼後的惡意腳本

    public function open_file() {
        if (file_exists($this->index)) {
            $content = file_get_contents($this->index);
            if (strrpos($content, $this->virus_type) !== false) {
                $clean = str_replace($this->virus_type, '', $content);
                $handle = fopen($this->index, 'w');
                fwrite($handle, $clean);
                fclose($handle);
                echo "病毒已清除:" . $this->index;
            } else {
                echo "未發現病毒特徵碼。";
            }
        } else {
            echo "檔案不存在:" . $this->index;
        }
    }
}

$scanner = new ClearVirus();
$scanner->open_file();
?>

使用注意事項

  • 僅能清除 完全相符 的特徵字串,駭客若調整編碼、插入空白或變更網域即可繞過。
  • 建議搭配 glob() 或遞迴掃描整個網站目錄,並記錄清除日誌。
  • 執行前務必備份原始檔案,避免誤刪正常程式碼。
  • 根本解決仍需修補上傳漏洞、設定嚴格的檔案寫入權限、部署 Web 應用程式防火牆(WAF)。

進階建議

若需更完整的掃描與清除,可考慮整合 PHP Malware Scanner 等開源專案,或使用 ClamAV、Linux Malware Detect (LMD) 等系統級工具定期掃描伺服器檔案。

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