Home Backend Development PHP Tutorial Detailed introduction to PHP security against injection_PHP tutorial

Detailed introduction to PHP security against injection_PHP tutorial

Jul 13, 2016 pm 05:10 PM
get php post web superior introduce Safety us submit number Way yes injection Know detailed

We know that there are two ways to submit data on the Web, one is get and the other is post. So many common SQL injections start from the get method, and the injection statements must contain some SQL statements. Because there is no sql statement, how to proceed? There are four major sentences in sql statement: select, update, delete, insert

So if we filter the data we submit, can we avoid these problems?
So we use regular expressions to construct the following function:

The code is as follows Copy code
 代码如下 复制代码

/*
函数名称:inject_check()
函数作用:检测提交的值是不是含有SQL注射的字符,防止注射,保护服务器安全
参 数:$sql_str: 提交的变量
返 回 值:返回检测结果,ture or false
函数作者:heiyeluren
*/

function inject_check($sql_str) 

     return eregi('select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile', $sql_str);    // 进行过滤 

 } 


 

/*

Function name: inject_check()

Function: Detect whether the submitted value contains SQL injection characters, prevent injection, and protect server security
 代码如下 复制代码

if (inject_check($_GET['id']))

{

exit('你提交的数据非法,请检查后重新提交!');

}

else

{

$id = $_GET['id'];

echo '提交的数据合法,请继续!';

}

?> 

Parameter: $sql_str: Submitted variable Return value: Return the detection result, true or false Function author: heiyeluren */ function inject_check($sql_str) { return eregi('select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile', $sql_str); // Filter }
In our function, we filter out all dangerous parameter strings such as select, insert, update, delete, union, into, load_file, outfile /*, ./, ../, ', etc., then we can control the submission parameters, the program can be constructed like this:
The code is as follows Copy code
<🎜>if (inject_check($_GET['id'])) <🎜> <🎜>{ <🎜> <🎜> exit('The data you submitted is illegal, please check and resubmit!'); <🎜> <🎜>} <🎜> <🎜>else <🎜> <🎜>{ <🎜> <🎜> $id = $_GET['id']; <🎜> <🎜> echo 'The submitted data is legal, please continue! '; <🎜> <🎜>} <🎜> <🎜>?>


Suppose we submit the URL as: a.php?id=1, then it will prompt:
"The submitted data is legal, please continue!"
If we submit a.php?id=1%27 select * from tb_name
A prompt will appear: "The data you submitted is illegal, please check and resubmit!"

Then our requirements are met.

However, the problem has not been solved yet. If we submit a.php?id=1asdfasdfasdf, ours is in compliance with the above rules, but it does not meet the requirements, so we try to solve other situations , we build another function to check:

The code is as follows Copy code
 代码如下 复制代码

/*
函数名称:verify_id()
函数作用:校验提交的ID类值是否合法
参 数:$id: 提交的ID值
返 回 值:返回处理后的ID
函数作者:heiyeluren
*/

function verify_id($id=null) 

   if (!$id) { exit('没有提交参数!'); }    // 是否为空判断 

   elseif (inject_check($id)) { exit('提交的参数非法!'); }    // 注射判断 

   elseif (!is_numeric($id)) { exit('提交的参数非法!'); }    // 数字判断 

   $id = intval($id);    // 整型化 

  

   return  $id; 


呵呵,那么我们就能够进行校验了,于是我们上面的程序代码就变成了下面的:

if (inject_check($_GET['id']))

{

exit('你提交的数据非法,请检查后重新提交!');

}

else

{

$id = verify_id($_GET['id']); // 这里引用了我们的过滤函数,对$id进行过滤

echo '提交的数据合法,请继续!';

}

?> 

/*

Function name: verify_id()
Function: Verify whether the submitted ID value is legal
Parameters: $id: Submitted ID value

Return value: Return the processed ID
 代码如下 复制代码

/*
函数名称:str_check()
函数作用:对提交的字符串进行过滤
参 数:$var: 要处理的字符串
返 回 值:返回过滤后的字符串
函数作者:heiyeluren
*/

function str_check( $str ) 

   if (!get_magic_quotes_gpc())    // 判断magic_quotes_gpc是否打开 

   { 

      $str = addslashes($str);    // 进行过滤 

 } 

     $str = str_replace("_", "_", $str);    // 把 '_'过滤掉 

     $str = str_replace("%", "%", $str);    // 把' % '过滤掉 

    

   return $str;  

Function author: heiyeluren */ function verify_id($id=null) { if (!$id) { exit('No parameters submitted!'); } // Determine whether it is empty elseif (inject_check($id)) { exit('The submitted parameter is illegal!'); } // Injection judgment elseif (!is_numeric($id)) { exit('The submitted parameter is illegal!'); } // Numerical judgment $id = intval($id); // Integerization return $id; } Haha, then we can perform verification, so our program code above becomes the following: <🎜>if (inject_check($_GET['id'])) <🎜> <🎜>{ <🎜> <🎜> exit('The data you submitted is illegal, please check and resubmit!'); <🎜> <🎜>} <🎜> <🎜>else <🎜> <🎜>{ <🎜> <🎜> $id = verify_id($_GET['id']); // Our filter function is quoted here to filter $id <🎜> <🎜> echo 'The submitted data is legal, please continue! '; <🎜> <🎜>} <🎜> <🎜>?>
Okay, the problem seems to be solved here, but have we considered the data submitted by post, the large batch of data? For example, some characters may cause harm to the database, such as '_', '%'. These characters have special meanings, so what if we control them? Another point is that when magic_quotes_gpc = off in our php.ini, the submitted data that does not comply with the database rules will not automatically be preceded by ' '. Then we need to control these problems, so we build it as follows Function:
The code is as follows Copy code
/* Function name: str_check() Function: Filter the submitted string Parameters: $var: string to be processed Return value: Return the filtered string Function author: heiyeluren */ function str_check( $str ) { if (!get_magic_quotes_gpc()) // Determine whether magic_quotes_gpc is turned on { $str = addslashes($str); // Filter } $str = str_replace("_", "_", $str); // Filter out '_' $str = str_replace("%", "%", $str); // Filter out '%' return $str; }


OK, we once again avoided the danger of the server being compromised.

Finally, consider the situation of submitting some large batches of data, such as posting, or writing articles or news. We need some functions to help us filter and convert. Based on the above functions, we build the following functions:

The code is as follows
 代码如下 复制代码

/*
函数名称:post_check()
函数作用:对提交的编辑内容进行处理
参 数:$post: 要提交的内容
返 回 值:$post: 返回过滤后的内容
函数作者:heiyeluren
*/

function post_check($post) 

   if (!get_magic_quotes_gpc())    // 判断magic_quotes_gpc是否为打开 

   { 

      $post = addslashes($post);    // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤 

   } 

   $post = str_replace("_", "_", $post);    // 把 '_'过滤掉 

   $post = str_replace("%", "%", $post);    // 把' % '过滤掉 

   $post = nl2br($post);    // 回车转换 

   $post= htmlspecialchars($post);    // html标记转换 

  

   return $post; 

Copy code
/* Function name: post_check()

Function: Process the submitted editing content

Parameters: $post: Content to be submitted Function author: heiyeluren */ function post_check($post) { if (!get_magic_quotes_gpc()) // Determine whether magic_quotes_gpc is turned on {
$post = addslashes($post); // Filter the submitted data when magic_quotes_gpc is not turned on }
$post = str_replace("_", "_", $post); // Filter out '_' $post = str_replace("%", "%", $post); // Filter out '%' $post = nl2br($post); // Enter conversion $post= htmlspecialchars($post); // html tag conversion return $post; } http://www.bkjia.com/PHPjc/629656.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629656.htmlTechArticleWe know that there are two ways to submit data on the Web, one is get and the other is post, so many common SQL injection starts from the get method, and the injection statement must contain 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
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

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.

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. 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: 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. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles