This article brings you an introduction to the method of comprehensively blocking SQL injection attacks in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
There may be many different types of attack motives, 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.
If your script is executing a SELECT instruction, then the attacker can force the display of each row of records in a table - by injecting a condition such as "1=1" into the WHERE clause, As shown below (where the injected part is shown in bold):
SELECT * FROM wines WHERE variety = 'lagrein' OR 1=1;'
As we commented earlier, this may be useful information in itself, as it reveals the general structure of the table (which is cannot be accomplished by a normal record), and records that potentially appear to contain confidential information.
An update command potentially poses a more direct threat. By putting other characteristics into the SET clause, an attacker can modify any field in the record that is being updated, such as the following example (in which the injected part is shown in bold):
UPDATE wines SET type='red','vintage'='9999' WHERE variety = 'lagrein'
Pass Add a 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 (in which the injected part is shown in bold):
UPDATE wines SET type='red','vintage'='9999 WHERE variety = 'lagrein' OR 1=1;'
Perhaps the most dangerous command is DELETE - it's not hard to imagine. The injection technique is the same as what we have already seen - by modifying the WHERE clause to expand the scope of the affected records, such as the following example (where the injected part is shown in bold):
DELETE FROM wines WHERE variety = 'lagrein' OR 1=1;'
Multiple Query Injections
Multiple query injections will increase the potential damage an attacker can cause - by allowing multiple destructive instructions to be included in a single query. When using a MySQL database, an attacker can easily accomplish this by inserting an unexpected stop character into the query - now an injected quote (single or double) marks the end of the desired variable; Then end the command with a semicolon. Now, an additional attack command may be added to the end of the now-stopped original command. The final destructive query might 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); in addition, there is a The "ominous" password is added to this simple SELECT sentence. If you followed our advice in the previous article and severely restricted 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 the reasons may be due to different versions of MySQL, but most of them are due to the way multiple queries exist. MySQL's monitoring program fully allows such a query. The commonly used MySQL GUI-phpMyAdmin will copy all previous content before the final query, and only do this.
However, most multiple queries in an injection context are managed by PHP's mysql extension. Fortunately, by default it does not allow executing multiple instructions in a query; attempting to execute two instructions (such as the injection shown above) will simply cause 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 (see http://php.net/mysqli), like mysql, does not inherently support multiple queries, but it provides a mysqli_multi_query() function to Supports you to complete multiple queries - if you really want to do so.
However, the situation with SQLite - the embeddable SQL database engine bundled with PHP5 (see http://sqlite.org/ and http://php.net/sqlite) is even more dire because of its ease of use The application has attracted the attention of many 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, if the results of the query are used by your script (for example, when using a SELECT sentence to retrieve records), the sqlite_query() function does not allow the execution of multiple queries.
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'");
Meanwhile, the member ID variable $mid and the password ID variable $pid are retrieved from the my_cookie() function using the following two lines of code:
$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 sentence:
return urldecode($_cookie[$ibforums->vars['cookie_id'].$name]);
【留意】从该cookie回来的值底子没有被处理。虽然$mid在运用于查询之前被强制转换成一个整数,可是$pid却保持不变。因而,它很容易遭受咱们前面所评论的注入类型的进犯。
因而,经过以如下方法修正my_cookie()函数,这种软弱性就会露出出来:
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]); }
经过这样的改正之后,其间的要害变量在"经过"全局clean_value()函数后被回来,而其它变量却未进行检查。
现在,已然咱们大致了解了什么是SQL注入,它的注入原理以及这种注入的软弱程度,那么接下来,让咱们探讨如何有用地防备它。幸亏,PHP为咱们供给了丰厚的资源,因而咱们有充沛的信心预言,一个经细心地彻底地运用咱们所引荐的技能构建的应用程序将会从你的脚本中底子上消除任何或许性的SQL注入-经过在它或许形成任何损坏之前"整理"你的用户的数据来完成。
The above is the detailed content of Introduction to methods to prevent SQL injection attacks in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

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.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

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 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 makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.