Home Backend Development PHP Tutorial Implementation code to prevent SQL injection in PHP_PHP tutorial

Implementation code to prevent SQL injection in PHP_PHP tutorial

Jul 21, 2016 pm 03:31 PM
php sql one No code but exist accomplish attack injection of type prevent

1. Types of Injection Attacks
There may be many different types of attack motivations, but at first glance, it seems that there are more types. This is very true - if a malicious user finds a way to perform multiple queries. We will discuss this in detail later in this article.
For example
If your script is executing a SELECT instruction, then an attacker can force the display of every row in a table - by injecting a condition such as "1=1" into the WHERE clause , as shown below (where the injection part is shown in bold):
SELECT * FROM wines WHERE variety = 'lagrein' OR 1=1;'

As we discussed earlier, this itself Can be useful information because it reveals the general structure of the table (something a plain record cannot), as well as potentially revealing records that contain confidential information.
An update directive potentially poses a more immediate threat. By placing other attributes in the SET clause, an attacker can modify any field in the record currently being updated, as in the following example (where the injected part is shown in bold):
UPDATE wines SET type= 'red', 'vintage'='9999' WHERE variety = 'lagrein'

By adding a constant true condition such as 1=1 to the WHERE clause of an update instruction, this modification range Can be extended to every record, such as the following example (where the injection part is shown in bold):
UPDATE wines SET type='red', 'vintage'='9999 WHERE variety = 'lagrein' OR 1=1 ;'

Probably the most dangerous instruction is DELETE - it's not hard to imagine. The injection technique is the same as what we've already seen - extending the scope of affected records by modifying the WHERE clause, as in the following example (where the injection part is in bold):
DELETE FROM wines WHERE variety = ' lagrein' OR 1=1;'

2. Multiple query injection
Multiple query injections will exacerbate the potential damage an attacker can cause - by allowing multiple Destructive instructions are included in a query. When using the MySQL database, an attacker can easily achieve this by inserting an unexpected terminator into the query - an injected quote (single or double) marks the end of the expected variable; Then terminate the directive with a semicolon. Now, an additional attack command may be added to the end of the now terminated original command. The final destructive query might look like this:

Copy code The code would look like this:

SELECT * FROM wines WHERE variety = 'lagrein';
GRANT ALL ON *.* TO 'BadGuy@%' IDENTIFIED BY 'gotcha';'

This injection will create a new user BadGuy and give it network privileges (all privileges on all tables); there is also an "ominous" password added to this simple SELECT statement. If you followed our advice in the previous article and strictly limited the privileges of the process user, then this should not work because the web server daemon no longer has the GRANT privileges that you revoked. But in theory, such an attack could give BadGuy free rein to do whatever he wants with your database.

As for whether such a multi-query will be processed by the MySQL server, the conclusion is not unique. Some of this may be due to different versions of MySQL, but most of the time it's due to the way multiple queries exist. MySQL's monitoring program fully allows such a query. The commonly used MySQL GUI-phpMyAdmin will copy out all previous content before the final query, and only do this.
However, most of the multiple queries within an injection context are managed by PHP's mysql extension. Fortunately, by default it does not allow executing multiple instructions in a query; trying to execute two instructions (such as the injection shown above) will simply cause a failure - no errors are set, and no output is generated information. In this case, although PHP only implements its default behavior "regularly", it can indeed protect you from most simple injection attacks.
The new mysqli extension in PHP5 (refer to http://php.net/mysqli), just like mysql, does not inherently support multiple queries, but it provides a mysqli_multi_query() function to support your implementation Multi-query - if you really want to do that.
However, for SQLite - the embeddable SQL database engine bundled with PHP5 (see http://sqlite.org/ and http://php.net/sqlite) the situation is even more dire, due to its ease of It has attracted the attention of a large number of users. In some cases, SQLite allows such multi-instruction queries by default because the database can optimize batch queries, especially batch INSERT statement processing, which is very efficient. However, the sqlite_query() function does not allow multiple queries to be executed if the results of the query are used by your script (for example, in the case of using a SELECT statement to retrieve records). 3. INVISION Power BOARD SQL injection vulnerability
Invision Power Board is a well-known forum system. On May 6, 2005, a SQL injection vulnerability was discovered in the login code. It was discovered
by James Bercegay of GulfTech Security Research.
This login query is as follows:
$DB->query("SELECT * FROM ibf_members WHERE id=$mid AND password='$pid'");

Where, member ID The variable $mid and the password ID variable $pid are retrieved from the my_cookie() function using the following two lines of code:
Copy code The code is as follows:

$mid = intval($std->my_getcookie('member_id'));
$pid = $std->my_getcookie('pass_hash');

Here, the my_cookie() function retrieves the requested variables from the cookie using the following statement:
return urldecode($_COOKIE[$ibforums->vars['cookie_id'].$name]);

【Note】The value returned from this cookie is not processed at all. Although $mid is cast to an integer before being used in the query, $pid remains unchanged. Therefore, it is vulnerable to the type of injection attacks we discussed earlier.
Therefore, by modifying the my_cookie() function in the following way, this vulnerability is exposed:
Copy code The code is as follows:

if ( ! in_array( $name, array('topicsread', 'forum_read', 'collapseprefs') ) )
{
return $this->
clean_value(urldecode( $_COOKIE[$ibforums->vars['cookie_id'].$name]));
}

else
{
return urldecode($_COOKIE[$ibforums-> vars['cookie_id'].$name]);
}

After such correction, the key variables are returned after "passing" the global clean_value() function, while other variables are not checked.
Now that we have a general understanding of what SQL injection is, how it works, and how vulnerable this injection is, let’s explore how to effectively prevent it. Fortunately, PHP provides us with a wealth of resources, so we can confidently predict that an application carefully and thoroughly built using our recommended techniques will essentially eliminate any possibility of SQL from your scripts. Injection - This is achieved by "cleaning" your user's data before it can cause any damage.
4. Define each value in your query
We recommend that you make sure you define each value in your query. String values ​​are the first to be affected, as are things you would normally expect to use "single" (rather than "double") quotes. On the one hand, if you use double quotes to allow PHP variable substitution within the string, it will make typing queries easier; on the other hand, this will (admittedly, only minimally) reduce the amount of PHP code in the future. analysis work.
Next, let us use the non-injection query we used at the beginning to illustrate this problem:
SELECT * FROM wines WHERE variety = 'lagrein'

Or expressed in PHP statement as:
$query = "SELECT * FROM wines WHERE variety = '$variety'";

Technically speaking, quotes are not required for numeric values. However, if you don't mind using quotes around a value for a field like wine and if your user enters a null value into your form, then you'll see a query like the following :
SELECT * FROM wines WHERE vintage =

Of course, this query is syntactically invalid; however, the following syntax is valid:
SELECT * FROM wines WHERE vintage = ' '

The second query will (probably) return nothing, but at least it won't return an error message.
5. Check the type of the value submitted by the user
From the previous discussion, we can see that so far, the main source of SQL injection often comes from an unexpected form entry. However, when you offer the user the opportunity to submit certain values ​​via a form, you should have a considerable advantage in determining
what input content you want to obtain - this can make it easier to check that the user entry is valid sex. In previous articles, we have discussed such verification issues; so, here we will only briefly summarize the main points of our discussion at that time. If you are expecting a number, then you can use one of these techniques to ensure that what you are getting is actually a numeric type: Use the is_int() function (or is_integer() or is_long()).
 · Use the gettype() function.
 · Use the intval() function.
 · Use the settype() function.
To check the length of user input, you can use the strlen() function. To check whether a desired time or date is valid, you can use the strtotime() function. It will almost certainly ensure that a user's entry does not contain a semicolon character (unless punctuation can be legally included). You can easily achieve this with the help of the strpos() function, as shown below:

if( strpos( $variety, ';' ) ) exit ( "$variety is an invalid value for variety!" ) ;

As we mentioned earlier, as long as you carefully analyze your user input expectations, you should be able to easily detect many problems.

6. Filter out every suspicious character from your query
Although in previous articles, we have discussed how to filter out dangerous characters; but here, let’s We simply emphasize and summarize this issue again:
· Do not use the magic_quotes_gpc instruction or its "behind-the-scenes partner"-addslashes() function. This function is restricted in application development, and this function also Requires an extra step - using the stripslashes() function.
· In comparison, the mysql_real_escape_string() function is more commonly used, but it also has its own shortcomings.

http://www.bkjia.com/PHPjc/322927.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322927.htmlTechArticle1. Types of injection attacks There may be many different types of attack motivations, but at first glance, there seem to be more Many types. This is very real - if a malicious user discovers a...
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