Home Backend Development PHP Tutorial Don't use addslashes and mysql_real_escape_string anymore to prevent SQL injection in PHP

Don't use addslashes and mysql_real_escape_string anymore to prevent SQL injection in PHP

Aug 08, 2016 am 09:30 AM
name pdo stmt string

The blogger is keen on various Internet technologies. He is often wordy and often accompanied by obsessive-compulsive disorder. He updates frequently. If you think the article is helpful to you, you can follow me. Please indicate "Dark Blue Sickle" when reprinting


I have seen that many PHP websites still use addslashes and str_replace to prevent SQL injection. Baidu's "PHP Anti-Injection" also uses them, and I found in practice Even mysql_real_escape_string has ways that hackers can bypass it. If your system is still using the above three methods , then my this blog post is meaningful to remind all latecomers to bypass this pit. .

For the sake of planting trees instead of digging holes for future generations, the version information of PHP and MYSQL is given so that the "problem" will no longer be a "problem" in the future.

It goes without saying that str_replace and various PHP character replacement functions are used to prevent injection. This "blacklist" type of defense has been proven to be unable to withstand the test of time.

The following is a method to bypass addslasher and mysql_real_escape_string (Trick).


Note: Although in MYSQL5.5.37 The Trick under -log has been fixed, but it is still not resolved exactly. Injection problem, because many companies' systems are still using Mysql5.0, I suggest making improvements immediately. This is also my "I will also talk about several methods for programmers to quickly improve their capabilities. A very important point mentioned in ".

Note: If you are not sure whether your system is at risk of SQL injection, please deploy the following DEMO to your server, if the running result Same, then please refer to the final perfect solution.

MYSQL:

mysql> select version();
+---------------------+
| version()           |
+---------------------+
| 5.0.45-community-ny |
+---------------------+
1 row in set (0.00 sec)
mysql> create database test default charset GBK;
Query OK, 1 row affected (0.00 sec)
mysql> use test;
Database changed
mysql> CREATE TABLE users (
    username VARCHAR(32) CHARACTER SET GBK,
    password VARCHAR(32) CHARACTER SET GBK,
    PRIMARY KEY (username)
);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into users SET username='ewrfg', password='wer44';
Query OK, 1 row affected (0.01 sec)
mysql> insert into users SET username='ewrfg2', password='wer443';
Query OK, 1 row affected (0.01 sec)
mysql> insert into users SET username='ewrfg4', password='wer4434';
Query OK, 1 row affected (0.01 sec)=
Copy after login

PHP:

<?php
echo "PHP version: ".PHP_VERSION."\n";

mysql_connect(&#39;servername&#39;,&#39;username&#39;,&#39;password&#39;);
mysql_select_db("test");
mysql_query("SET NAMES GBK");

$_POST[&#39;username&#39;] = chr(0xbf).chr(0x27).&#39; OR username = username /*&#39;;
$_POST[&#39;password&#39;] = &#39;guess&#39;;

$username = addslashes($_POST[&#39;username&#39;]);
$password = addslashes($_POST[&#39;password&#39;]);
$sql = "SELECT * FROM  users WHERE  username = &#39;$username&#39; AND password = &#39;$password&#39;";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);

var_dump(mysql_num_rows($result));
var_dump(mysql_client_encoding());

$username = mysql_real_escape_string($_POST[&#39;username&#39;]);
$password = mysql_real_escape_string($_POST[&#39;password&#39;]);
$sql = "SELECT * FROM  users WHERE  username = &#39;$username&#39; AND password = &#39;$password&#39;";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);

var_dump(mysql_num_rows($result));
var_dump(mysql_client_encoding());

mysql_set_charset("GBK");
$username = mysql_real_escape_string($_POST[&#39;username&#39;]);
$password = mysql_real_escape_string($_POST[&#39;password&#39;]);
$sql = "SELECT * FROM  users WHERE  username = &#39;$username&#39; AND password = &#39;$password&#39;";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);

var_dump(mysql_num_rows($result));
var_dump(mysql_client_encoding());
Copy after login

Result:
PHP version: 5.2.5
int(3)
string(6) "latin1"
int(3)
string(6) "latin1"
int(0)
string(3) "gbk" 
Copy after login
It can be seen that whether using addslashes or mysql_real_escape_string,I can use coding vulnerabilities to achieve injection attacks that allow me to log in to the server by entering any password! ! ! ! (I won’t go into details about the principle of the attack. Interested students can study the single-byte and multi-byte issues in character encoding)

Note: The reason why the third mysql_real_escape_string can prevent injection is Because mysql_escape_string itself cannot determine the current encoding, you must specify the server encoding and the client encoding at the same time. This can prevent the injection of encoding problems. Although SQL injection can be prevented to a certain extent, the following perfect solution is still recommended.

The perfect solution is to use PDO and MYSQLi with Prepared Statement mechanism to replace mysql_query (Note: mysql_query has been deprecated since PHP 5.5.0 and will be removed in the future):

PDO :

$pdo = new PDO(&#39;mysql:dbname=dbtest;host=127.0.0.1;charset=utf8&#39;, &#39;user&#39;, &#39;pass&#39;);

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}
Copy after login

MYSQLi :

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}
Copy after login

The above introduces how to prevent SQL injection in PHP. Don’t use addslashes and mysql_real_escape_string anymore. It includes the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Jun 22, 2023 pm 06:40 PM

PHP is a popular web development language that has been used for a long time. The PDO (PHP Data Object) class integrated in PHP is a common way for us to interact with the database during the development of web applications. However, a problem that some PHP developers often encounter is that when using the PDO class to interact with the database, they receive an error like this: PHPFatalerror:CalltoundefinedmethodPDO::prep

PHP and PDO: How to perform bulk inserts and updates PHP and PDO: How to perform bulk inserts and updates Jul 28, 2023 pm 07:41 PM

PHP and PDO: How to perform batch inserts and updates Introduction: When using PHP to write database-related applications, you often encounter situations where you need to batch insert and update data. The traditional approach is to use loops to perform multiple database operations, but this method is inefficient. PHP's PDO (PHPDataObject) provides a more efficient way to perform batch insert and update operations. This article will introduce how to use PDO to implement batch insert and update operations. 1. Introduction to PDO: PDO is PH

Convert basic data types to strings using Java's String.valueOf() function Convert basic data types to strings using Java's String.valueOf() function Jul 24, 2023 pm 07:55 PM

Convert basic data types to strings using Java's String.valueOf() function In Java development, when we need to convert basic data types to strings, a common method is to use the valueOf() function of the String class. This function can accept parameters of basic data types and return the corresponding string representation. In this article, we will explore how to use the String.valueOf() function for basic data type conversions and provide some code examples to

How to convert char array to string How to convert char array to string Jun 09, 2023 am 10:04 AM

Method of converting char array to string: It can be achieved by assignment. Use {char a[]=" abc d\0efg ";string s=a;} syntax to let the char array directly assign a value to string, and execute the code to complete the conversion.

PHP and PDO: How to perform paging queries and display data PHP and PDO: How to perform paging queries and display data Jul 29, 2023 pm 04:10 PM

PHP and PDO: How to query and display data in pages When developing web applications, querying and displaying data in pages is a very common requirement. Through paging, we can display a certain amount of data at a time, improving page loading speed and user experience. In PHP, the functions of paging query and display of data can be easily realized using the PHP Data Object (PDO) library. This article will introduce how to use PDO in PHP to query and display data by page, and provide corresponding code examples. 1. Create database and data tables

PHP and PDO: How to perform a full-text search in a database PHP and PDO: How to perform a full-text search in a database Jul 30, 2023 pm 04:33 PM

PHP and PDO: How to perform a full-text search in a database In modern web applications, the database is a very important component. Full-text search is a very useful feature when we need to search for specific information from large amounts of data. PHP and PDO (PHPDataObjects) provide a simple yet powerful way to perform full-text searches in databases. This article will introduce how to use PHP and PDO to implement full-text search, and provide some sample code to demonstrate the process. first

PHP PDO vs. mysqli: compare and contrast PHP PDO vs. mysqli: compare and contrast Feb 19, 2024 pm 12:24 PM

PDOPDO is an object-oriented database access abstraction layer that provides a unified interface for PHP, allowing you to use the same code to interact with different databases (such as Mysql, postgresql, oracle). PDO hides the complexity of underlying database connections and simplifies database operations. Advantages and Disadvantages Advantages: Unified interface, supports multiple databases, simplifies database operations, reduces development difficulty, provides prepared statements, improves security, supports transaction processing Disadvantages: performance may be slightly lower than native extensions, relies on external libraries, may increase overhead, demo code uses PDO Connect to mysql database: $db=newPDO("mysql:host=localhost;dbnam

PHP and PDO: How to handle JSON data in a database PHP and PDO: How to handle JSON data in a database Jul 29, 2023 pm 05:17 PM

PHP and PDO: How to handle JSON data in databases In modern web development, processing and storing large amounts of data is a very important task. With the popularity of mobile applications and cloud computing, more and more data are stored in databases in JSON (JavaScript Object Notation) format. As a commonly used server-side language, PHP's PDO (PHPDataObject) extension provides a convenient way to process and operate databases. Book

See all articles