


A brief introduction to SQL injection attacks in PHP vulnerabilities_PHP tutorial
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 |

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
