search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP security against injection_PHP tutorial

Detailed introduction to PHP security against injection_PHP tutorial

Jul 13, 2016 pm 05:10 PM
getphppostwebsuperiorintroduceSafetyussubmitnumberWayyesinjectionKnowdetailed

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
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

DVWA

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment