如何解決網(wǎng)頁內(nèi)容安全問題?使用rhukster/dom-sanitizer可以!

可以通過以下地址學習 composer學習地址

在開發(fā)一個允許用戶提交網(wǎng)頁內(nèi)容的項目時,確保這些內(nèi)容的安全性是至關重要的。我遇到的一個具體問題是,用戶可能會在 html、svg 或 mathml 文件中嵌入惡意代碼,導致潛在的安全漏洞。為了解決這個問題,我嘗試了多種方法,但效果不盡如人意。最終,我發(fā)現(xiàn)了 rhukster/dom-sanitizer 這個庫,它專為 php 7.4+ 設計,能夠有效地清理和過濾危險的標簽和屬性。

安裝這個庫非常簡單,只需使用 Composer:

composer require rhukster/dom-sanitizer

rhukster/dom-sanitizer 借鑒了 JavaScript 庫 DOMPurify 的標簽和屬性列表,并使用 PHP 的 DOMDocument 來解析和過濾 DOM。這個庫提供了多種選項,可以根據(jù)需要定制清理過程。例如,你可以選擇是否移除命名空間、PHP 標簽、HTML 標簽、xml 標簽,以及是否壓縮輸出。

使用這個庫,你可以輕松地清理 HTML、SVG 和 MathML 內(nèi)容。例如,要清理 HTML 內(nèi)容,你可以這樣做:

require 'vendor/autoload.php';  use RhuksterDomSanitizerDOMSanitizer;  $input = file_get_contents('bad.html');  $sanitizer = new DOMSanitizer(DOMSanitizer::HTML); $output = $sanitizer->sanitize($input, [     'remove-html-tags' => false, ]);

如果你專門處理 SVG 內(nèi)容,可以這樣做:

require 'vendor/autoload.php';  use RhuksterDomSanitizerDOMSanitizer;  $input = file_get_contents('bad.svg'); $sanitizer = new DOMSanitizer(DOMSanitizer::SVG); $output = $sanitizer->sanitize($input);

對于 MathML 內(nèi)容,清理過程同樣簡單:

require 'vendor/autoload.php';  use RhuksterDomSanitizerDOMSanitizer;  $input = file_get_contents('mathml-sample.xml'); $sanitizer = new DOMSanitizer(DOMSanitizer::MATHML); $output = $sanitizer->sanitize($input, [     'compress-output' => false, ]);

rhukster/dom-sanitizer 還允許你自定義允許或不允許的標簽和屬性。你可以使用以下方法來修改這些設置:

public function addAllowedTags(array $allowed_tags): void  public function addAllowedAttributes(array $allowed_attributes): void  public function addDisallowedTags(array $disallowed_tags): void  public function addDisallowedAttributes(array $disallowed_attributes): void  public function getAllowedTags(): array  public function setAllowedTags(array $allowed_tags): void  public function getAllowedAttributes(): array  public function setAllowedAttributes(array $allowed_attributes): void  public function getDisallowedTags(): array  public function setDisallowedTags(array $disallowed_tags): void  public function getDisallowedAttributes(): array  public function setDisallowedAttributes($disallowed_attributes): void

使用 rhukster/dom-sanitizer 后,我的項目在處理用戶提交的內(nèi)容時變得更加安全和高效。這個庫不僅解決了我的安全問題,還提供了高度的靈活性,使得自定義清理過程變得簡單而有效。如果你在處理網(wǎng)頁內(nèi)容時遇到類似的安全問題,強烈推薦你嘗試使用 rhukster/dom-sanitizer。

? 版權聲明
THE END
喜歡就支持一下吧
點贊5 分享