Home Backend Development PHP Tutorial Understand some methods of sql injection in php yourself_PHP tutorial

Understand some methods of sql injection in php yourself_PHP tutorial

Jul 13, 2016 pm 05:10 PM
php sql under learn introduce method injection of Own

Understand some of the methods of sql injection in php. The following are all the most common sql injection methods. Friends in need can refer to them.

What is injection?

For example, when we query the database, we retrieve all the information of this article through the article's ID number. Then the SQL statement can be written like this:

The code is as follows Copy code
 代码如下 复制代码

select * from blog where id=5 

select * from blog where id=5

The value of id is passed through the user's operation, usually in the GET method, in the form of read.php?id=5. There seems to be no problem with this, but if we change the SQL statement slightly:
 代码如下 复制代码

select * from blog where id=5 or 1=1 

The code is as follows Copy code

select * from blog where id=5 or 1=1

1=1 is the same, then this statement will retrieve all articles. To modify this, you only need to change the value passed by GET: read.php?id='5 or 1=1'; pay attention to these two single quotes... So the simplest thing is that we can directly change the parameters to Single quotes to see if this link is injected. Of course, it doesn't matter if illegal users see all the articles, but what if this table stores account numbers and passwords?

2. How to prevent injection?

In the final analysis, the key to preventing injection lies in character filtering, because illegal users generally pass values ​​by constructing URLs. If we filter the illegal parameters they pass in, the illegal SQL statements will not be executed. , then we will prevent the website from being injected!

 代码如下 复制代码

function safe($s) 

    if(!get_magic_quotes_gpc()) 

    { 

        if(is_array($s)) 

            foreach($s as $key=>$value) 

                $s[$key] = addslashes($value); 

        else 

            $s=addslashes($s); 

    } 

    return $s; 

 

function html_safe($s) 

    return nl2br(htmlspecialchars(safe($s) )) ; 

PHP’s built-in filter string is quite good, let’s take a look at the specific code first:
The code is as follows Copy code
function safe($s) { if(!get_magic_quotes_gpc()) { if(is_array($s)) foreach($s as $key=>$value) $s[$key] = addslashes($value); else $s=addslashes($s); } return $s; } function html_safe($s) { return nl2br(htmlspecialchars(safe($s) )) ; }

If you don’t know the built-in functions used above and are too lazy to check the manual, then I will talk about these functions:

magic_quotes_gpc is called magic quotes. If this function is turned on, then when inserting data into the database, what the magic quotes do is to automatically apply the addslashes() function to all GET, POST, and COOKIE data. get_magic_quotes_gpc() is used to get whether this function is turned on on the server: if it is turned on, then the data is returned directly; if it is not turned on, then the parameters are manually escaped with addslashes(). This will prevent double-level escaping~

addslashes – Use backslashes to quote strings. Description: string addslashes (string str); returns a string with backslashes added before certain characters for database query statements, etc. These characters are single quotes ('), double quotes ("), backslash () and NUL (NULL character). An example of using addslashes() is when you are entering data into a database. For example, changing the name O 'reilly is inserted into the database, which requires escaping it. Most databases use as escape character: O'reilly. This allows the data to be inserted into the database without inserting additional . When turned on, it means that ' will be escaped when inserting '

.

The htmlspecialchars below converts characters in Html, such as converting '&' to '&', and converting '<' to '<'. nl2br converts carriage return and line feed into
. This is often used when users enter information such as comments.

Through the above functions, we can already filter some simple injections. In addition, let’s talk about a few small aspects:

As for the initial example, there are actually many areas for improvement. For example, it should look more standardized when written like this:

The code is as follows Copy code
 代码如下 复制代码

SELECT * FROM `blog` WHERE `id`='$id' 

SELECT * FROM `blog` WHERE `id`='$id'

For SQL keywords, we use uppercase letters. For tables and fields in the database, we use lowercase letters. In addition, add the "·" symbol to the field names and table names (on the key to the left of the number 1 on the keyboard) , and we use single quotes on the incoming id.

For such incoming parameters that are of numeric type, we can force convert the value obtained by $_GET. But I’m more used to this:
 代码如下 复制代码

$id = $_GET['id']*1; //获取文章的id,用来显示文章信息 

if($id == 0){ 

echo "ERROR..."; 

exit(); 

The code is as follows Copy code

$id = $_GET['id']*1; //Get the id of the article to display article information

if($id == 0){

echo "ERROR...";

 代码如下 复制代码

if ( !get_magic_quotes_gpc() ) { 

    $_GET = add_slashes($_GET); 

    $_POST = add_slashes($_POST); 

    $_COOKIE = add_slashes($_COOKIE); 

exit(); }
If it is found that the passed in number is not a number, then it is very likely that there is a problem with the parameters, then we can directly give an error message and exit, so as not to perform database query operations for illegal users. Finally, let’s take a look at a place in JBlog that handles injection: Line 38 of includecommon.php
The code is as follows Copy code
if ( !get_magic_quotes_gpc() ) { $_GET = add_slashes($_GET); $_POST = add_slashes($_POST); $_COOKIE = add_slashes($_COOKIE); }

Line 194 of includefunc_global.php

function add_slashes($string) {
The code is as follows
 代码如下 复制代码

//addslashes 

function add_slashes($string) { 

    if (!is_array($string)) return addslashes($string); 

    foreach ($string as $key => $val) { 

        $string[$key] = add_slashes($val); 

    } 

    return $string; 


 

Copy code

//addslashes

if (!is_array($string)) return addslashes($string);

foreach ($string as $key => $val) {

} return $string; }
Of course, this should be only part of it, and the rest should be similar.
http://www.bkjia.com/PHPjc/629655.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629655.htmlTechArticleUnderstand some of the methods of sql injection in php. The following are all the most common sql injection methods. There are Friends in need can refer to it. What is injection? For example, we are querying data...
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles