search
Homephp教程php手册php 防止查询的sql攻击方法总结

防止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;)";

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

htmlentities($name,ENT_NOQUOTES,GB2312).


Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment