1.strip_tags();
把所有輸入內容內的html語法跟js碼去掉
用法:
strip_tags($mystring);
2.htmlspecialchars();
htmlspecialchars是最基本的防線,在strip_tags過濾後加上htmlspecialchars過濾可以把strip_tags處理不掉的部分,如"或'轉換成文字碼(譬如:" 會變成")
也有人說strip_tags可以不做但是htmlspecialchars一定要
用法:
htmlspecialchars($mystring);2.mb_substr();
輸入的字數先砍長度,譬如限制最多只有500或5000,防止mysql欄位的溢位攻擊
建議加上utf-8,以防內容有英數字會造成砍完長度後的尾字變亂碼
ex: mb_substr( $string,0,500,"utf-8"); //只截取500字
3.mysql_real_escape_string:
過濾敏感字元,防sql_injection,加這道前mysql要先建立資料庫連結,有登入的欄位最好加上
例如:
$con=mysqli_connect("localhost","db_userName","db_passWord","dbName");
mysqli_real_escape_string($con, $value);
如果有紀錄ip的話,可多加一道
4.用正規表示式去掉ip非數字跟 . 的部分,防sql_injection跟xss()攻擊,或用php內建的ip檢查函式檢查:
//取得使用者ip if(!empty($_SERVER['HTTP_CLIENT_IP'])){ $i_useripServer = $_SERVER['HTTP_CLIENT_IP']; }else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ $i_useripServer = $_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $i_useripServer= $_SERVER['REMOTE_ADDR']; } $i_userip = filter_var($i_useripServer, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
sql的陳述式最好參數化處理,以避免SQL injection的風險:$myData=$_POST['data'];
$sql="INSERT INTO tableName (t_data) VALUES ('{$myData}')";
例如原本下面的方式:
$query="SELECT * FROM dbName WHERE t_userid = '$userId'"; $result=mysqli_query($link,$query); $count=mysqli_num_rows($result);
最好改為下面的參數化陳述
$query = "SELECT * FROM dbName WHERE t_userid = ?"; $stmt = $link->prepare($query); $stmt->bind_param('s',$userId); $stmt->execute(); $result = $stmt->get_result(); $count=mysqli_num_rows($result); if($count>0){ $row=mysqli_fetch_array($result); $dataOne = $row['data_one']; $dataTwo = $row['data_two']; } $stmt->free_result(); $stmt->close(); $mysqli->close();
沒有留言:
張貼留言