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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles