当前位置:软件学堂 > 资讯首页 > 网络编程 > 编程其他 > JavaScript过滤SQL注入字符

JavaScript过滤SQL注入字符

2012/10/22 19:47:16作者:佚名来源:网络

移动端

【实例名称】

JavaScript 过滤 SQL 注入字符

【实例描述】

由于大多数的数据提交语句都是通过多个字符串进行连接,所以为了防止SQL 的注入字符,本例介绍一种过滤特殊字符的方法。 


【实例代码】

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>标题页</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>

【运行效果】

运行效果

【难点剖析】

本例的重点是对特殊字符的判断。sQL需要防范的注入字符在代码中被一一列举,使用“indexOF”方法,可以判断字符串中是否包含这些字符。如果“indexOf”返回“一1”,则表示不包含指定的特殊字符。

【源码下载】

本实例JS代码下载

 

标签: 字符