Home > php教程 > php手册 > body text

php 防止查询的sql攻击方法总结

WBOY
Release: 2016-05-25 16:41:36
Original
1284 people have browsed it

防止sql注入不但是新学的程序员朋友需要深入了解的一个重要知识点之外,还是我们这些写了多年程序的朋友也必须注意的东西,下面给新手介绍php 防止查询的sql攻击的一些例子,希望对各位会有所帮助.

一个入门级别的例子,代码如下:

$k = $_REQUEST['k']; 
$k = addslashes($k);//转义:单引号,双引号,反斜线,NULL 
$k = str_replace('%', '\%', $k); 
$k = str_replace('_', '\_', $k); 
$sql = "select * from users where name like '%$k%'"; 
if(!emptyempty($k)){ 
$res = mysql_query($sql, $con) or die(mysql_error()); 
if($row = mysql_fetch_assoc($res)){ 
    foreach($row as $k=>$v){ 
        echo $row[$k].&#39;:&#39;.$row[$v].&#39;<br />&#39;; 
    } 
} 
}else{ 
    echo &#39;******&#39;; 
} 
补充:mysql_real_escape_string();所以得SQL语句如果有类似这样的写法:
"select * from cdr where src =".$userId; 都要改成 $userId=mysql_real_escape_string($userId) 
例子代码如下:
<?php 
$clean = array(); 
$mysql = array(); 
$clean[&#39;last_name&#39;] = "O&#39;Reilly"; 
$mysql[&#39;last_name&#39;] = mysql_real_escape_string($clean[&#39;last_name&#39;]); 
$sql = "INSERT 
      INTO   user (last_name) 
      VALUES (&#39;{$mysql[&#39;last_name&#39;]}&#39;)";
Copy after login

所有有打印的语句如echo,print等,在打印前都要使用htmlentities() 进行过滤,这样可以防止Xss,注意中文要写出,代码如下:

htmlentities($name,ENT_NOQUOTES,GB2312).


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!