Home Backend Development PHP Tutorial Analysis Summary of Comprehensive Prevention of SQL Injection Attacks in PHP_PHP Tutorial

Analysis Summary of Comprehensive Prevention of SQL Injection Attacks in PHP_PHP Tutorial

Jul 21, 2016 pm 03:21 PM
php sql one comprehensive analyze strength introduction powerful attack yes injection Prevent

1. Introduction

PHP is a powerful but easy-to-learn server-side scripting language. Even programmers with little experience can use it to create complex and dynamic web site. However, it often has many difficulties in realizing the confidentiality and security of Internet services. In this series of articles, we will introduce readers to the security background necessary for web development as well as PHP-specific knowledge and code - you can use it to protect the security and consistency of your own web applications. First, we briefly review server security issues - showing how you can access private information in a shared hosting environment, keep developers off production servers, maintain up-to-date software, provide encrypted channels, and control access to your systems. access.

We then discuss common vulnerabilities in PHP script implementations. We'll explain how to protect your scripts from SQL injection, prevent cross-site scripting and remote execution, and prevent "hijacking" of temporary files and sessions.

In the last article, we will implement a secure web application. You'll learn how to authenticate users, authorize and track application usage, avoid data loss, safely execute high-risk system commands, and use web services securely. Whether you have sufficient experience in PHP security development or not, this series of articles will provide a wealth of information to help you build more secure online applications.

2. What is SQL injection

If you plan to never use certain data, then there is no point in storing it in a database; because the database It is designed to facilitate access and manipulation of data in the database. However, simply doing so can lead to potential disaster. This is not the case primarily because you yourself may accidentally delete everything in the database; it is because, while you are trying to complete some "innocent" task, you may be "hijacked" by someone - using himself of destructive data to replace your own data. We call this replacement "injection".

In fact, every time you ask a user for input to construct a database query, you are allowing that user to participate in constructing a command to access the database server. A friendly user might feel satisfied implementing such an operation; however, a malicious user will try to find a way to twist the command, causing the twisted command to delete data or even do something more dangerous. things. As a programmer, your task is to find a way to avoid such malicious attacks.

3. How SQL injection works

Constructing a database query is a very straightforward process. Typically, it will be implemented along the following lines. Just to illustrate the problem, we will assume that you have a wine database table "wines" with a field "variety" (i.e. wine type):

 1. Provide a form - allow the user to submit certain requirements What to search for. Let's assume the user chooses to search for wines of type "lagrein".

2. Retrieve the user's search term and save it - by assigning it to a variable like this:

Here is the code snippet:

$variety = $_POST['variety'];

Therefore, the value of variable $variety is now:

lagrein

3. Then, use this variable in the WHERE subsection Construct a database query in the sentence:

The following is the code snippet:

$query = "SELECT * FROM wines WHERE variety='$variety'";

Therefore, variables The value of $query now looks like this:

The following is the code snippet:

SELECT * FROM wines WHERE variety='lagrein'

4. Submit the query to MySQL server.

5. MySQL returns all records in the wines table - among them, the value of field variety is "lagrein".

By now, this should be a familiar and very easy process. Unfortunately, sometimes the processes we are familiar with and comfortable with can easily lead to complacency. Now, let's reanalyze the query we just constructed.

1. The fixed part of the query you create ends with a single quote, which you will use to describe the beginning of the variable value:

Here is the code snippet:

$query = " SELECT * FROM wines WHERE variety = '";

 2. Use the original fixed part and contain the value of the variable submitted by the user:

 The following is a code snippet :

$query .= $variety;

3. You then use another single quote to concatenate this result - describing the end of the variable value:

Here is Code snippet:

$ query .= "'";

Therefore, the value of $query is as follows:

The following is a code snippet:

SELECT * FROM wines WHERE variety = 'lagrein'

  The success of this construct relies on user input. In this example, you are using a single word (or possibly a group of words) to specify a type of wine.Therefore, the query is constructed without any problems, and the result is what you would expect - a list of wines with the wine type "lagrein". Now, let's imagine that instead of entering a simple wine type of type "lagrein", your user enters the following (note the two punctuation marks included):

 lagrein' or 1=1;

Now, you continue to construct your query using the previously fixed parts (here, we only show the result value of the $query variable):

SELECT * FROM wines WHERE variety = '

You then concatenate it with the value of the variable containing the user input (shown here in bold):

SELECT * FROM wines WHERE variety = 'lagrein ' or 1=1;

Finally, add the lower quotes:

SELECT * FROM wines WHERE variety = 'lagrein' or 1=1;'

So , the query results will be quite different from what you expect. In fact, your query now contains not one but two instructions, because the final semicolon entered by the user has ended the first instruction (performing record selection) and started a new instruction. In this case, the second instruction means nothing other than a simple single quote; however, the first instruction is not what you want to implement either. When the user puts a single quote in the middle of his input, he ends up expecting the value of the variable and introduces another condition. So instead of retrieving those records whose variety is "lagrein", we are retrieving records that satisfy either of two criteria (the first is yours and the second is his - variety is "lagrein" or 1 Records equal to 1). Since 1 is always 1, therefore, you will retrieve all records!

You may object: Wouldn’t I use double quotes instead of single quotes to describe user-submitted variables? Yes, this can at least reduce Slow attacks by malicious users. (In a previous article, we reminded you that all error notification messages to the user should be disabled. If an error message is generated here, it may just help the attacker - provide an explanation as to why his attack failed. Specific explanation. )

In practice, enabling your users to see all records rather than just some of them may seem like a hassle at first, but in reality, it does; see Retrieving all the records would easily provide him with information about the internal structure of the table, thus providing him with an important reference for further more nefarious purposes. The situation just described is especially true if your database contains, instead of the apparently innocuous information about alcohol, a list of employees' annual earnings.

From a theoretical perspective, this kind of attack is indeed a terrible thing. By injecting unexpected content into your query, this user is able to transform your database access for his own purposes. So now, your database is open to him - as it is to you.

IV. PHP and MySQL Injection

As we described earlier, PHP, by design, does not do anything special - except follow your instructions beyond the instructions. Therefore, if used by a malicious user, it would only "allow" specially designed attacks - such as the one we described earlier - as required.

We're going to assume that you don't intentionally or even accidentally construct a database query that has destructive effects - so we're going to assume that the problem is with the input from your users. Now, let's take a closer look at the various ways users might provide information to your script.

5. Types of user input

Today, the ways users can influence the behavior of your scripts have become increasingly complex.

The most obvious source of user input is, of course, a text input field on a form. By using a field like this, you are literally encouraging a user to enter arbitrary data. Furthermore, you provide the user with a large input range; there is no way for you to limit in advance the type of data a user can enter (although you can choose to limit its length). This is why the vast majority of injection attacks originate from unsuspecting form fields.

However, there are other sources of attacks, and if you think about it for a moment, you will think of a technology hidden behind the form - the POST method! By simply analyzing the content displayed in the browser's navigation toolbar URI, an observant user can easily see what information is passed to a script. Although such URIs are typically generated programmatically, there is nothing to prevent a malicious user from simply entering a URI with an inappropriate variable value into a browser - and potentially Opens a database that could be abused.

A common strategy for limiting user input is to provide a select box in a form instead of an input box. This type of control can force the user to choose from a predefined set of values ​​and can prevent the user from entering unexpected content to a certain extent.But just as an attacker might "spoof" a URI (i.e., create one that mimics a trustworthy but invalid URI), he might also be able to mimic your form and create his own version of it, and therefore create a new version of the URI in the option box. Use illegal instead of predefined safe options. To achieve this is extremely simple; he just needs to look at the source code, then cut and paste the source code of the form - and then everything opens up for him.

After modifying the selection, he will be able to submit the form and his invalid commands will be accepted as if they were the original commands. Therefore, the user can use many different methods to attempt to inject malicious code into a script.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324885.htmlTechArticle1. Introduction PHP is a server-side scripting language that is powerful but fairly easy to learn, even with little experience. Programmers can also use it to create complex dynamic web sites. However...
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
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
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 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: 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 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