Table of Contents
PHP injection attack prevention example analysis, PHP injection example analysis
What is the best way to prevent SQL injection in php?
[Repost] How to prevent PHP SQL injection attacks
Home Backend Development PHP Tutorial PHP injection attack prevention example analysis, PHP injection example analysis_PHP tutorial

PHP injection attack prevention example analysis, PHP injection example analysis_PHP tutorial

Jul 13, 2016 am 10:15 AM
php attack injection prevent

PHP injection attack prevention example analysis, PHP injection example analysis

This article provides a detailed analysis of PHP's methods of preventing injection attacks in the form of examples. Share it with everyone for your reference. The specific analysis is as follows:

PHP addslashes() function --single apostrophe plus slash escape

PHP String Function

Definition and usage

The addslashes() function adds a backslash before the specified predefined characters.
These predefined characters are:
Single quote (')
Double quotes (")
Backslash ()
NULL
Syntax:

addslashes(string)

Parameters Description
参数  描述
string 必需。规定要检查的字符串。
string Required. Specifies the string to check.

Tips and Notes

Tip: This function can be used to prepare appropriate strings for strings stored in the database and database query statements.
Note: By default, the PHP directive magic_quotes_gpc is on, automatically running addslashes() on all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it.

Example

In this example, we want to add a backslash to a predefined character in the string:

Copy code The code is as follows:
$str = "Who's John Adams?";
echo $str . " This is not safe in a database query.
";
echo addslashes($str) . " This is safe in a database query.";
?>

Output:
Who's John Adams? This is not safe in a database query.
Who's John Adams? This is safe in a database query.

get_magic_quotes_gpc function

Copy code The code is as follows:
function html($str)
{
$str = get_magic_quotes_gpc()?$str:addslashes($str);
Return $str;
}

get_magic_quotes_gpc:
Get the value of the PHP environment variable magic_quotes_gpc.
Syntax: long get_magic_quotes_gpc(void);
Return value: long integer
Function type: PHP system function

Content description:

This function obtains the value of the variable magic_quotes_gpc (GPC, Get/Post/Cookie) set in the PHP environment. Returning 0 means turning off this function; returning 1 means turning this function on. When magic_quotes_gpc is enabled, all ' (single quote), " (double quote), (backslash) and null characters will be automatically converted to overflow characters containing backslash.

addslashes --Use backslashes to quote strings

Description:

string addslashes ( string str)
Returns a string with backslashes added in front of certain characters for the purpose of database query statements, etc. These characters are single quote ('), double quote ("), backslash () and NUL (NULL character).

An example of using addslashes() is when you are entering data into a database. For example, inserting the name O'reilly into the database requires escaping it. Most databases use as escape character: O'reilly. This puts the data into the database without inserting extra . When the PHP directive magic_quotes_sybase is set to on, it means that inserting ' will be escaped with '.

By default, the PHP instruction magic_quotes_gpc is on, which mainly automatically runs addslashes() on all GET, POST and COOKIE data. Do not use addslashes() on strings that have been escaped by magic_quotes_gpc, as this will result in double escaping. When encountering this situation, you can use the function get_magic_quotes_gpc() to detect it.

Example 1. addslashes() example

Copy code The code is as follows:
$str = "Is your name O'reilly?";
// Output: Is your name O'reilly?
echo addslashes($str);
?>
get_magic_quotes_gpc()

This function obtains the value of the variable magic_quotes_gpc (GPC, Get/Post/Cookie) in the PHP environment configuration. Returning 0 means turning off this function; returning 1 means turning this function on. When magic_quotes_gpc is turned on, all ' (single quote), " (double quote), (backslash) and null characters will automatically be converted to overflow characters containing backslash.

magic_quotes_gpc

For magic_quotes_gpc in php.ini, should it be set to off or on?

Personal opinion, should be set to on

The summary is as follows:

1. For magic_quotes_gpc=on,

We can not do anything with the string data of the input and output databases
For the operations of addslashes() and stripslashes(), the data will be displayed normally.

If you perform addslashes() on the input data at this time,
Then you must use stripslashes() to remove excess backslashes when outputting.

2. For the case of magic_quotes_gpc=off

You must use addslashes() to process the input data, but you do not need to use stripslashes() to format the output
Because addslashes() does not write the backslashes into the database, it just helps mysql complete the execution of the sql statement.

Supplement:

magic_quotes_gpc Scope is: WEB client server; Time of action: When the request starts, such as when the script is running.
magic_quotes_runtime Scope: Data read from a file or the result of executing exec() or obtained from a SQL query; Time of action: Every time the script accesses data generated in the running state

Code:

Copy code The code is as follows:
/*
Sometimes there is more than one variable submitted in a form, maybe a dozen or dozens. So is it a little troublesome to copy/paste addslashes() again and again? Since the data obtained from the form or URL appears in the form of an array, such as $_POST, $_GET), then customize a function that can "sweep the army"
*/
function quotes($content)
{
//If magic_quotes_gpc=Off, then start processing
if (!get_magic_quotes_gpc()) {
//Determine whether $content is an array
if (is_array($content)) {
//If $content is an array, then process each of its elements
foreach ($content as $key=>$value) {
$content[$key] = addslashes($value);
}
} else {
//If $content is not an array, then it will only be processed once
addslashes($content);
}
} else {
//If magic_quotes_gpc=On, then it will not be processed
}
//Return $content
return $content;
}
?>

I hope this article will be helpful to everyone’s PHP programming design.

What is the best way to prevent SQL injection in php?

If the user input is a query that is inserted directly into a SQL statement, the application will be vulnerable to SQL injection, such as the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO table ( column) VALUES ('" . $unsafe_variable . "')"); This is because the user can enter something like VALUE "); DROP TABLE table; - , making the query become: Use prepared statements and parameterized queries. SQL statements with any parameters will be sent to the database server and parsed! It is impossible for an attacker to maliciously inject SQL! There are basically two options to achieve this goal: 1. Use PDO (PHP Data Objects): $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array(':name' => $name)); foreach ($stmt as $ row) { // do something with $row }2. Use 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 }PDO(PHP Data Object) Note that real prepared statements are not used by default when using PDO! To solve this problem, you must disable emulation of prepared statements. An example of using PDO to create a connection is as follows: $dbConnection = new PDO(' mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO: :ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);The error mode ERRMODE is not strictly required in the above example, but it is recommended to add it. This method does not stop the script when a fatal error occurs. And give the developer a chance to catch any errors (when PDOException is thrown). The setAttribute() line is mandatory, it tells PDO to disable emulated prepared statements and use real prepared statements. This ensures that statements and values ​​are not parsed by PHP before being sent to the MySQL database server (an attacker has no chance of injecting malicious SQL). Of course you can set the character set parameter in the constructor options, paying special attention to 'old' PHP versions ( 5.3.6) will ignore the character set parameter in the DSN. The most important thing here is that the parameter value is combined with a precompiled statement, not with a SQL string. The working principle of SQL injection is that the SQL script created by deception includes a malicious string... The rest of the full text>>

[Repost] How to prevent PHP SQL injection attacks

I think the most important point is to check and escape data types. The following rules are summarized: The display_errors option in php.ini should be set to display_errors = off. In this way, after an error occurs in the php script, the error will not be output on the web page to prevent attackers from analyzing useful information. When calling mysql functions such as mysql_query, @ should be added in front, that is, @mysql_query(...), so that mysql errors will not be output. The same is true to prevent attackers from analyzing useful information. In addition, some programmers are used to outputting errors and sql statements when mysql_query errors when developing, for example: $t_strSQL = "SELECT a from b....";
if ( mysql_query($t_strSQL) ){ //Correct processing}else{echo "Error! SQL statement: $t_strSQL \r\nError message".mysql_query();exit;} This approach is quite dangerous and stupid. If you must do this, it is best to set a global variable or define a macro in the website configuration file and set the debug flag: In the global configuration file:
define("DEBUG_MODE",0); // 1: DEBUG MODE; 0: RELEASE MODE
//Calling script:

php /****************************** Description : Determine whether the passed variables contain illegal characters such as $_POST, $_GET Function: Anti-injection**************************/ //Required Filtered illegal characters $ArrFiltrate=array("'",";","union"); //The url to be jumped after an error occurs. If not filled in, the previous page will be defaulted. $StrGoUrl=""; //Whether there is an array The value in function FunStringExist($StrFiltrate,$ArrFiltrate){ foreach ($ArrFiltrate as $key=>$value){ if (eregi($value,$StrFiltrate)){ returntrue; } } returnfalse; } //Merge $ _POST and $_GETif(function_exists(array_merge)){ $ArrPostAndGet=array_merge($HTTP_POST_VARS,$HTTP_GET_VARS); }else{ foreach($HTTP_POST_VARS as $key=>$value){ $ArrPostAndGet[]=$value; } foreach ($HTTP_GET_VARS as $key=>$value){ $ArrPostAndGet[]=$value; } } //Verification starts foreach($ArrPostAndGet as $key=>$value){ if (FunStringExist($value,$ArrFiltrate )){ echo "alert(\"Illegal character\");"; if (empty($StrGoUrl)){ echo &q...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/904916.htmlTechArticlePHP prevent injection attack example analysis, php injection example analysis This article analyzes in detail how PHP prevents injection attacks in the form of examples . Share it with everyone for your reference. The specific analysis is as follows:...
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 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles