search
HomeBackend DevelopmentPHP TutorialHow to implement form submission data verification processing function in PHP

这篇文章主要介绍了PHP实现表单提交数据的验证处理功能,可实现防SQL注入和XSS攻击等,涉及php字符处理、编码转换相关操作技巧,需要的朋友可以参考下

防XSS攻击代码:

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
 $string = str_replace('%20','',$string);
 $string = str_replace('%27','',$string);
 $string = str_replace('%2527','',$string);
 $string = str_replace('*','',$string);
 $string = str_replace('"','"',$string);
 $string = str_replace("'",'',$string);
 $string = str_replace('"','',$string);
 $string = str_replace(';','',$string);
 $string = str_replace(&#39;<&#39;,&#39;<&#39;,$string);
 $string = str_replace(&#39;>&#39;,&#39;>&#39;,$string);
 $string = str_replace("{",&#39;&#39;,$string);
 $string = str_replace(&#39;}&#39;,&#39;&#39;,$string);
 $string = str_replace(&#39;\\&#39;,&#39;&#39;,$string);
 return $string;
}

代码实例:

<?php
$user_name = strim($_REQUEST[&#39;user_name&#39;]);
function strim($str)
{
 //trim() 函数移除字符串两侧的空白字符或其他预定义字符。
 //htmlspecialchars() 函数把预定义的字符转换为 HTML 实体(防xss攻击)。
 //预定义的字符是:
 //& (和号)成为 &
 //" (双引号)成为 "
 //&#39; (单引号)成为 &#39;
 //< (小于)成为 <
 //> (大于)成为 >
 return quotes(htmlspecialchars(trim($str)));
}
//防sql注入
function quotes($content)
{
 //if $content is an array
 if (is_array($content))
 {
  foreach ($content as $key=>$value)
  {
   //$content[$key] = mysql_real_escape_string($value);
   /*addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。
   预定义字符是:
   单引号(&#39;)
   双引号(")
   反斜杠(\)
   NULL */
   $content[$key] = addslashes($value);
  }
 } else
 {
  //if $content is not an array
  //$content=mysql_real_escape_string($content);
  $content=addslashes($content);
 }
 return $content;
}
?>

//过滤sql注入
function filter_injection(&$request)
{
 $pattern = "/(select[\s])|(insert[\s])|(update[\s])|(delete[\s])|(from[\s])|(where[\s])/i";
 foreach($request as $k=>$v)
 {
    if(preg_match($pattern,$k,$match))
    {
      die("SQL Injection denied!");
    }
    if(is_array($v))
    {
     filter_injection($request[$k]);
    }
    else
    {
     if(preg_match($pattern,$v,$match))
     {
      die("SQL Injection denied!");
     }
    }
 }
}

防sql注入:

mysql_real_escape_string() 函数转义 SQL 语句中使用的字符串中的特殊字符。

下列字符受影响:

\x00
\n
\r
'

\x1a

如果成功,则该函数返回被转义的字符串。如果失败,则返回 false。

语法

mysql_real_escape_string(string,connection)


参数 描述
string 必需。 规定要转义的字符串。
connection 可选。 规定 MySQL 连接。如果未规定,则使用上一个连接。

对于纯数字或数字型字符串的校验可以用

is_numeric()检测变量是否为数字或数字字符串

实例:

<?php 
function get_numeric($val) { 
 if (is_numeric($val)) { 
 return $val + 0; 
 } 
 return 0; 
} 
?>

is_array — 检测变量是否是数组
bool is_array ( mixed $var ) <br>如果 var 是 array,则返回 TRUE,否则返回 FALSE。

is_dir 判断给定文件名是否是一个目录
bool is_dir ( string $filename ) <br>判断给定文件名是否是一个目录。
如果文件名存在,并且是个目录,返回 TRUE,否则返回FALSE。

is_file — 判断给定文件名是否为一个正常的文件
bool is_file ( string $filename ) <br>判断给定文件名是否为一个正常的文件。
如果文件存在且为正常的文件则返回 TRUE,否则返回 FALSE。
Note:
因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型,对 2GB 以上的文件,一些文件系统函数可能返回无法预期的结果 。

is_bool — 检测变量是否是布尔型
bool is_bool ( mixed $var )<br>如果 var 是 boolean 则返回 TRUE。

is_string — 检测变量是否是字符串
bool is_string ( mixed $var ) <br>如果 var 是 string 则返回 TRUE,否则返回 FALSE。

is_int — 检测变量是否是整数
bool is_int ( mixed $var ) <br>如果 var 是 integer 则返回 TRUE,否则返回 FALSE。
Note:
若想测试一个变量是否是数字或数字字符串(如表单输入,它们通常为字符串),必须使用 is_numeric()。

is_float — 检测变量是否是浮点型
bool is_float ( mixed $var ) <br>如果 var 是 float 则返回 TRUE,否则返回 FALSE。
Note:
若想测试一个变量是否是数字或数字字符串(如表单输入,它们通常为字符串),必须使用 is_numeric()。

is_null — 检测变量是否为 NULL
bool is_null ( mixed $var ) <br>如果 var 是 null 则返回 TRUE,否则返回 FALSE。

is_readable — 判断给定文件名是否可读
bool is_readable ( string $filename )<br>判断给定文件名是否存在并且可读。如果由 filename 指定的文件或目录存在并且可读则返回 TRUE,否则返回 FALSE。

is_writable — 判断给定的文件名是否可写
bool is_writable ( string $filename ) <br>如果文件存在并且可写则返回 TRUE。filename 参数可以是一个允许进行是否可写检查的目录名。

file_exists — 检查文件或目录是否存在
bool file_exists ( string $filename ) <br>检查文件或目录是否存在。
在 Windows 中要用 //computername/share/filename 或者 \computername\share\filename 来检查网络中的共享文件。
如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE。

is_executable — 判断给定文件名是否可执行
bool is_executable ( string $filename )<br>判断给定文件名是否可执行。如果文件存在且可执行则返回 TRUE,错误时返回FALSE。

相关推荐:

解决php 处理 form 表单提交多个 name 属性值相同的 input 标签问题

python模拟表单提交登录图书馆

使用Ajax进行Form表单提交步骤详解

The above is the detailed content of How to implement form submission data verification processing function in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment