search
HomeBackend DevelopmentPHP TutorialImplementation 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
phpsqloneNocodebutexistaccomplishattackinjectionoftypeprevent

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
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor