當(dāng)前位置:軟件學(xué)堂 > 資訊首頁(yè) > 網(wǎng)絡(luò)編程 > 編程其他 > JavaScript過(guò)濾SQL注入字符

JavaScript過(guò)濾SQL注入字符

2012/10/22 19:47:16作者:佚名來(lái)源:網(wǎng)絡(luò)

移動(dòng)端

【實(shí)例名稱】

JavaScript 過(guò)濾 SQL 注入字符

【實(shí)例描述】

由于大多數(shù)的數(shù)據(jù)提交語(yǔ)句都是通過(guò)多個(gè)字符串進(jìn)行連接,所以為了防止SQL 的注入字符,本例介紹一種過(guò)濾特殊字符的方法。 


【實(shí)例代碼】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>標(biāo)題頁(yè)</title> <script LANGUAGE="JavaScript"> function check(inputStr) {    if (typeof(inputStr) != "string") { return inputStr; } //判斷是否是字符串類型    var tmpValue = inputStr;     //以下搜索字符串中的特殊字符,如果存在,則替換成""     while (tmpValue.indexOf(';') > -1) {tmpValue = tmpValue.replace(';',''); }     while (tmpValue.indexOf('<') > -1) {tmpValue = tmpValue.replace('<',''); }     while (tmpValue.indexOf('>') > -1) {tmpValue = tmpValue.replace('>',''); }     while (tmpValue.indexOf('--') > -1) {tmpValue = tmpValue.replace('--',''); }    while (tmpValue.indexOf(",") > -1) {tmpValue = tmpValue.replace(",",""); }    while (tmpValue.indexOf("'") > -1) {tmpValue = tmpValue.replace("'",""); }    while (tmpValue.indexOf("?") > -1) {tmpValue = tmpValue.replace("?",""); }    document.getElementById("txt1").value = tmpValue;  //重新顯示更改后的變量 } </script> </head> <body> <input type=text id="txt1" value="select * from userinfo where username=zhang' and passwrod=2" style="width: 392px"> <input type=button value="提交" onClick="check(txt1.value)"> </body> </html>

【運(yùn)行效果】

運(yùn)行效果

【難點(diǎn)剖析】

本例的重點(diǎn)是對(duì)特殊字符的判斷。sQL需要防范的注入字符在代碼中被一一列舉,使用“indexOF”方法,可以判斷字符串中是否包含這些字符。如果“indexOf”返回“一1”,則表示不包含指定的特殊字符。

【源碼下載】

本實(shí)例JS代碼下載

 

標(biāo)簽: JavaScript  字符