- 相關(guān)推薦
正則表達(dá)式過(guò)濾HTML危險(xiǎn)腳本的實(shí)例
導(dǎo)語(yǔ):在做一些網(wǎng)站(特別是bbs之類)時(shí),經(jīng)常會(huì)有充許用戶輸入html樣式代碼,卻禁止腳本的運(yùn)行的需求, 以達(dá)到豐富網(wǎng)頁(yè)樣式,禁止惡意代碼的運(yùn)行。以下的是百分網(wǎng)小編為大家搜集的正則表達(dá)式過(guò)濾HTML危險(xiǎn)腳本的實(shí)例,希望對(duì)你會(huì)有所幫助。
不能用 htmlencode 和 htmldecode 方法,因?yàn)檫@樣連基本的html代碼會(huì)被禁止掉。
以下是一些腳本攻擊的實(shí)例:
1. <script>標(biāo)記中包含的代碼
2. <a href=javascript:...中的代碼
3. 其它基本控件的 on...事件中的代碼
4. iframe 和 frameset 中載入其它頁(yè)面造成的攻擊
有了這些資料后,事情就簡(jiǎn)單多了,下面簡(jiǎn)單的方法,用正則表達(dá)式把以上符合幾點(diǎn)的代碼替換掉:
public string wipescript(string html)
{
system.text.regularexpressions.regex regex1 = new system.text.regularexpressions.regex(@"<script[ss]+</script *>",system.text.regularexpressions.regexoptions.ignorecase);
system.text.regularexpressions.regex regex2 = new system.text.regularexpressions.regex(@" href *= *[ss]*script *:",system.text.regularexpressions.regexoptions.ignorecase);
system.text.regularexpressions.regex regex3 = new system.text.regularexpressions.regex(@" on[ss]*=",system.text.regularexpressions.regexoptions.ignorecase);
system.text.regularexpressions.regex regex4 = new system.text.regularexpressions.regex(@"<iframe[ss]+</iframe *>",system.text.regularexpressions.regexoptions.ignorecase);
system.text.regularexpressions.regex regex5 = new system.text.regularexpressions.regex(@"<frameset[ss]+</frameset *>",system.text.regularexpressions.regexoptions.ignorecase);
html = regex1.replace(html, ""); //過(guò)濾<script></script>標(biāo)記
html = regex2.replace(html, ""); //過(guò)濾href=javascript: (<a>) 屬性
html = regex3.replace(html, " _disibledevent="); //過(guò)濾其它控件的on...事件
html = regex4.replace(html, ""); //過(guò)濾iframe
html = regex5.replace(html, ""); //過(guò)濾frameset
return html;
}
此方法輸入可能包含腳本的html代碼,返回則就是干凈的代碼了。
【正則表達(dá)式過(guò)濾HTML危險(xiǎn)腳本的實(shí)例】相關(guān)文章:
php過(guò)濾危險(xiǎn)html代碼的方法09-17
php過(guò)濾HTML標(biāo)簽、屬性等正則表達(dá)式07-19
HTML用正則表達(dá)式檢驗(yàn)表格的實(shí)例代碼08-11
C#實(shí)現(xiàn)協(xié)同過(guò)濾算法的實(shí)例代碼06-19
如何實(shí)現(xiàn)PHP獲取表單數(shù)據(jù)與HTML嵌入PHP腳本09-23
HTML實(shí)現(xiàn)頁(yè)面自動(dòng)跳轉(zhuǎn)的方法有哪些(實(shí)例)07-31