


SQL injection is an attack that allows an attacker to add additional logical expressions and commands to an existing SQL query. This attack is able to succeed whenever the data submitted by the user is not properly validated and stuck with a legitimate SQL queries are together, so SQL injection attacks are not a problem of PHP but a problem of programmers.
General steps for SQL injection attacks:
1. Attackers visit sites with SQL injection vulnerabilities and look for injection points
2. The attacker constructs an injection statement, and the injection statement is combined with the SQL statement in the program to generate a new SQL statement
3. The new sql statement is submitted to the database for execution
4. The database executed a new SQL statement, triggering a SQL injection attack
Examples
Database
CREATE TABLE `postmessage` (
`id` int(11) NOT NULL auto_increment,
`subject` varchar(60) NOT NULL default ",
`name` varchar(40) NOT NULL default ",
`email` varchar(25) NOT NULL default ",
`question` mediumtext NOT NULL,
`postdate` datetime NOT NULL default '0000-00-00 00:00:00′,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=gb2312 COMMENT='User's Message' AUTO_INCREMENT=69;
grant all privileges on ch3.* to 'sectop'@localhost identified by '123456′;
//add.php insert message
//list.php message list
//show.php Show messages
Page /show.php?id=71 There may be an injection point, let’s test it
/show.php?id=71 and 1=1
Return to page
Once the record was queried, once there was no record, let’s take a look at the source code
//show.php lines 12-15
// Execute mysql query statement
$query = "select * from postmessage where id = ".$_GET["id"];
$result = mysql_query($query)
or die("Failed to execute ySQL query statement: " . mysql_error());
After the parameter id is passed in, the sql statement combined with the previous string is put into the database to execute the query
Submit and 1=1, the statement becomes select * from postmessage where id = 71 and 1=1. The values before and after this statement are both true, and after and is also true, and the queried data is returned
Submit and 1=2, the statement becomes select * from postmessage where id = 71 and 1=2. The first value of this statement is true, the last value is false, and the next value is false, and no data can be queried
A normal SQL query, after passing through the statement we constructed, forms a SQL injection attack. Through this injection point, we can further obtain permissions, such as using union to read the management password, read database information, or use mysql's load_file, into outfile and other functions to further penetrate.
Anti-SQL injection methods
$id = intval ($_GET['id']);
Of course, there are other variable types. If necessary, try to force the format.
Character parameter:
Use the addslashes function to convert single quotes "'" to "'", double quotes """ to """, backslashes "" to "", and NULL characters plus backslashes ""
Function prototype
string addslashes (string str)
str is the string to be checked
Then we can fix the code vulnerability that just appeared
// Execute mysql query statement
$query = "select * from postmessage where id = ".intval($_GET["id"]);
$result = mysql_query($query)
or die("Failed to execute ySQL query statement: " . mysql_error());
If it is a character type, first determine whether magic_quotes_gpc can be On. If it is not On, use addslashes to escape the special characters
The code is as follows | Copy code | ||||
|
The SQL statement contains variables with quotes
SQL code:
The code is as follows | Copy code | ||||
SELECT * FROM article WHERE articleid = $id
|
3. URL pseudo-static
URL pseudo-static is URL rewriting technology, like Discuz! Similarly, it is a good idea to rewrite all URLs into a format similar to xxx-xxx-x.html, which is beneficial to SEO and achieves a certain level of security. But if you want to prevent SQL injection in PHP, you must have a certain "regular" foundation.
4. Use PHP functions to filter and escape
The more important point of SQL injection in PHP is the setting of GPC, because versions below MYSQL4 do not support sub-statements, and when magic_quotes_gpc in php.ini is On, all " ' " in the submitted variables (single quotation marks), " " " (double quotation marks), " " (backslash) and null characters will automatically be converted into escape characters containing backslashes, which brings a lot of obstacles to SQL injection.
5. Use PHP’s MySQL function to filter and escape
PHP’s MySQL operation functions include addslashes(), mysql_real_escape_string(), mysql_escape_string() and other functions, which can escape special characters or characters that may cause database operation errors.
So what are the differences between these three functional functions? Let’s talk about it in detail below:
① The problem with addslashes is that hackers can use 0xbf27 to replace single quotes, while addslashes just changes 0xbf27 to 0xbf5c27, which is called a valid multi-byte character. 0xbf5c is still regarded as a single quote, so addslashes cannot Successfully intercepted.
Of course, addslashes is not useless. It is used for processing single-byte strings. For multi-byte characters, use mysql_real_escape_string.
代码如下 | 复制代码 |
if(!get_magic_quotes_gpc()){ $lastname = addslashes($_POST['lastname']);}else{ $lastname = $_POST['lastname'];} |
In addition, for the example of get_magic_quotes_gpc in the php manual:
The code is as follows | Copy code |
if(!get_magic_quotes_gpc()){ $lastname = addslashes($_POST['lastname']);}else{ $lastname = $_POST['lastname'];}
|
代码如下 | 复制代码 |
function daddslashes($string, $force = 0, $strip = FALSE) { if(!MAGIC_QUOTES_GPC || $force) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = daddslashes($val, $force, $strip); } } else { $string = addslashes($strip ? stripslashes($string) : $string); } } return $string; } |
The code is as follows | Copy code |
function daddslashes($string, $force = 0 , $strip = FALSE) { if(!MAGIC_QUOTES_GPC || $force) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = daddslashes($val, $force, $strip); } } else { $string = addslashes($strip ? stripslashes($string) : $string); } } return $string; } |
Command 1 - Write arbitrary file
MySQL has a built-in command that can be used to create and write system files. The format of this command is as follows:
The code is as follows
|
Copy code
|
||||||||||||||||
mysq> select "text" INTO OUTFILE "file.txt"
Command 2 - Read any file |

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),