search
HomeBackend DevelopmentPHP Tutorialphp表单敏感字符过滤类_php技巧

本文实例讲述了php表单敏感字符过滤类及其用法。分享给大家供大家参考。具体分析如下:

复制代码 代码如下:

/**
* 表单生成验证文件
*/
$_form = new formHtmlFind();
class formHtmlFind{
        /**
         * 输出表单函数
         * $formKey  表单键
         * $infoArray 更新时的原始信息数组
         */
 
        public function formHtml($array,$infoArray='')
        {
                // 检测数组是否存在
                if(emptyempty($array))return false;
                $newform = null;
                // 信息数组(更新信息)
                $this->infoArray = !emptyempty($infoArray)?$infoArray:array();
                $this->array['class'] =  get_class_methods(get_class());
                foreach ($array as $key =>$arr)
                {
                        // 键值转换为纯英文
                        $key = preg_replace("/[^a-z]/i",'',$key);
                        // 生成表单
                        $newform .= $this->outputForm($arr,$key);
                }
                // 输出表单
                return $newform.$this->jsError();
        }
        /**
         * 生成表单函数
         */
        private function outputForm($arr,$key)
        {
                $value = null;
                if(emptyempty($arr))return false;
                // input Type
                $type   = $key;
                // input NAME
                $name   = trim($arr[0]);
                // input 初始值 不包含多选,单选类
                $value  = (!emptyempty($this->infoArray[$name]))? trim($this->infoArray[$name]):trim($arr[1]);
                $value  = emptyempty($this->post[$name])? $value :trim($this->post[$name]);
                // input Title
                $title  = trim($arr[2]);
                // 样式
                $style  = trim($arr[3]);
                if($key!=="hidden")
                {
                        $dt = "
{$title}
";
                        // js错误提示
                        $dd = "
rn";
                }
                return (!preg_match("/checkbox|select|radio/i",$key))?
                $dt.$this->newInput($type,$name,$value,$style,$title).$dd:
                $this->formSelect($type,$name,$arr[1],$title,$style); // 多选类
        }
        /**
         * 提交数据检测
         */
        public function postForm($array)
        {
                // 检测数组是否存在
                if(emptyempty($array)||emptyempty($_POST))return false;
                $this->post           =  $_POST;
                $this->array['class'] =  get_class_methods(get_class());
                foreach ($array as $key =>$arr)
                {
                        // 键值转换为纯英文
                        $key = preg_replace("/[^a-z]/i",'',$key);
                        // 检测 注销file类表单
                        if (!emptyempty($arr)&&'file' != $key)$newData[trim($arr[0])] = $this->postFind($arr,$key);
                }
                // 输出表单
                if(!emptyempty($this->error))
                {
                        return false;
                }
                else return $newData;
        }
        /**
         * 生成表单
         */
        private function newInput($type,$name,$value,$style,$title)
        {
                switch ($type)
                {
                        case 'text':
                                // 单行文本
                                return  "";
                                break;
                        case 'password':
                                //密码输入
                                return "";
                                break;
                        case '':
                                //多行文本
                                return "{$value}";
                                break;
                        case 'hidden':
                                // 隐藏
                                return "";
                                break;
                        case 'file':
                                // 文件上传
                                return "";
                                break;
                        case 'submit':
                                // 提交
                                return "";
                                break;
                        default:
                                return "{$type}类型错误!!!";
                                break;
                }
        }
        /**
         * 提交信息检测
         * 错误返回error
         */
        private function postFind($arr,$key)
        {
                if(emptyempty($arr))return false;
                $name = $title =$error =$find =$standard =null;
                // input NAME
                $name     = trim($arr[0]);
                // input Title
                $title    = trim($arr[2]);
                // 错误提示
                $error    = trim($arr[4]);
                // 检测类型 Y N
                $find     = trim($arr[5]);
                // 检测标准
                $standard = trim($arr[6]);
                //
                if(!emptyempty($standard))$this->error .=$this->ck_split($standard,$name,$title,$find,$error);
                // 转换为字符串
                if(is_array($this->post[$name]))$this->post[$name] = implode(",",$this->post[$name]);
                // 转义或其他转化
                $KKarray = array();
                if(preg_match("/Y|N/is",$find))
                {
                        $KKarray       = split("_", $find);
                        // 转义或过滤
                        $escape_filter = (!emptyempty($KKarray[1]))?'ck_'.$KKarray[1]:'';
                        // 输出通过检测的合法数据
                        $data          = ($escape_filter)?$this->$escape_filter($this->post[$name]):$this->post[$name];
 
                }
                else  $data        = "";
                // 输出新的数据
                return $data;
        }
        /**
         * 多选类表单生成
         */
        private function formSelect($type,$name,$value,$title,$style)
        {
                $outform = null;
                // 触发更新和提交动作时的初始
                $nowvalue = (!emptyempty($this->post[$name]))?$this->post[$name]:$this->infoarray[$name];
                // 兼容多选的识别,转为数组
                if(!emptyempty($nowvalue))$valueArray = explode(",",$nowvalue);
                // 选项标题
                if(is_array($title))
                {
                        array_unshift($title,'选择');
                        $titarray = array_values($title);
                }else $titarray = explode("|",$title);
                // 选项值
                if(is_array($value))
                {
                        array_unshift($value,'选择');
                        $valarray  = array_keys($value);
                        if(emptyempty($title))$titarray = array_values($value);
                }
                else $valarray = explode("|",$value);
                // 取消表单的初始默认值
                if(!emptyempty($this->post)&&!emptyempty($this->infoArray))$value = preg_replace("/Y_/i",'',$value);
 
                foreach ($valarray as $key =>$varl)
                {
                        // 非默认的识别
                        if(!emptyempty($valueArray))$select   = (in_array($varl,$valueArray))?'Y':'';
                        //  判断是否为默认
                        else $select   = (eregi("Y_",$varl))? 'Y':'';
 
                        if($key >'0')
                        {
                                $_title=($titarray[$key])? $titarray[$key]:$title;
                                switch ($type)
                                {
                                        case 'select':
                                                if('Y' == $select)$select = 'selected';
                                                $outform .=        sprintf("%srn"
                                                ,$select,preg_replace("/Y_/i",'',$varl),$_title);
                                                break;
                                        case 'radio':
                                                if('Y' == $select)$select = 'checked';
                                                $outform .= sprintf("rn",
                                                $_title,$select,$name,$varl,$style);
                                                break;
                                        case 'checkbox':
                                                if('Y' == $select)$select = 'checked';
                                                $outform .= sprintf("rn",$_title,$select,$name,$varl,$style);
                                                break;
                                }
                                $select =null;
                        }
                }
                // 下拉选择
                if($type =='select')$outform = sprintf('',$name,$style,$outform);
                return sprintf("
%s
%s
rn",$titarray[0],$outform,$name);
        }
        /**
         * 表单验证 及全部 ck_类函数
         */
        private function ck_split($standard,$name,$title,$find,$error)
        {
                //  非必填缺省跳过
                if(eregi('N',$find) && emptyempty($this->post[$name]))return false;
                // 必填缺省检测
                if(eregi('Y',$find) && emptyempty($this->post[$name]))return "["J{$name}","$error"],";
                $t_error = null;
                // 多项检测
                $arr = explode(',',$standard);
                // POST数据检测
                if(!emptyempty($arr))foreach ($arr as $var)
                {
                        if(trim($var)!='')
                        {
                                switch ($this->post)
                                {
                                        case is_array($this->post[$name]):
                                                // 数组类的检测
                                                foreach ($this->post[$name] as $_var)
                                                {
                                                        $t_error.= ($this->ck_open($_var,trim($var)))?"":$error;
                                                        if($t_error)break;
                                                }
                                                break;
                                        default:
                                                $t_error.= ($this->ck_open($this->post[$name],trim($var)))?"":$error;
                                                break;
                                }
                                if($t_error)break;
                        }
                }
                return ($t_error)? "["J{$name}","$t_error"],":"";
        }
        // 函数调用
        private function ck_open($string,$str)
        {
                $functi = $this->ck_detected($str);
                return ($this->$functi($string,$str))? true:false;
        }
        // 类型判断
        private function ck_detected($str)
        {
                $detect = (eregi("^[a-zA-Z]*$",$str))? "{$str}Detect":'lengthDetect';
                if(!in_array($detect,$this->array['class']))
                {
                        location('index.php',$ck,' Lack of function !!!');
                }
                return $detect;
        }
        //-------------------------------------以下为检测函数可外部调用
        // 长度
        public function lengthDetect($string,$str){
                $len = split('-',trim($str));
                return (strlen($string) > ($len[0]-1) && strlen($string)         }
        // 价格
        public function moneyDetect($str){
                return preg_match("/^(-|+)?d+(.d+)?$/",$str);
        }
        // 邮件
        public function emailDetect($str){
                return preg_match("/^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/", $str);
        }
        // 网址
        public function urlDetect($str){
                return preg_match("/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*([^"])*$/", $str);
        }
        // 数字型
        public function numDetect($str){
                return is_numeric($str);
        }
        // 中文
        public function cnDetect($str){
                return preg_match("/^[x7f-xff]+$/", $str);
        }
        // 字母
        public function enDetect($str){
                return preg_match("/^[A-Za-z]+$/", $str);
        }
        // 数字字母混合
        public function numenDetect($str){
                return preg_match("/^([a-zA-Z0-9_-])+$/",$str);
        }
        // 电话号码
        public function telDetect($str){
                return ereg("^[+]?[0-9]+([xX-][0-9]+)*$", $str);
        }
        // 敏感词
        public function keyDetect($str){
                return (!preg_match("/$badkey/i",$str));
        }
        //-----------------------------------------------------输出
        // 字符替换
        public function ck_filter($str){
                $str=(is_array($str))? implode(",",$str):$str;
                $str=nl2br($str); //将回车替换为

                $str=htmlspecialchars($str); //将特殊字元转成 HTML 格式。
                //$str=str_replace(array(" ",'                 return $str;
        }
        // 转义
        function ck_escape($str)
        {
                if (!get_magic_quotes_gpc())return addslashes($str);
                return $str;
        }
        // MD5加密
        public function ck_md5($str){
                return  MD5($str);
        }
        // base64加密
        public function ck_base64($str){
                return  base64_encode($str);
        }
        // 时间
        function ck_time($str){
                // time_r() 来在公用函数文件
                if(!is_numeric($str))
                {
                        return time_r($str);
                }
                else return $str;
        }
        // 有条件注销(数字)
        public function ck_cancel($str){
                return (!is_numeric($str))? $str:"";
        }
        // 无条件注销
        public function ck_delete(){
                return null;
        }
        // js错误提示
        private function jsError()
        {
                if(emptyempty($this->error))return false;
                return  "
               
                ";
        }
}
 
// 演示:
$form[1] =array(
'text'=>array('title','','产品名称','size=40','产品名称不可缺少!','Y','cn,1-30'),
'text1'=>array('categories','','产品名称','','','Y_base64'),
'select'=>array('superiors','||1|2|Y_3','产品类别|选择|1|2|3','','必选项','Y'),
'radio'=>array('superiors1','|1|Y_2|3','产品xun|产品1|产品2|产品3','','必选项','Y'),
'checkbox'=>array('superiors2',array(1=>'11',2=>'22',3=>'33'),'','','必选项','Y'),
'file'=>array('ddd','','文件'),
);
$form =array (
  'login' => 
  array (
    'text' => 
    array (
      0 => 'user',
      1 => '',
      2 => '用户名',
      3 => 'size=20',
      4 => '!',
      5 => 'Y',
      6 => 'numen,6-12',
    ),
    'password' => 
    array (
      0 => 'pass',
      1 => '',
      2 => '密 码',
      3 => 'size=22',
      4 => '密码格式错误!',
      5 => 'Y_md5',
      6 => 'numen,6-12',
    ),
    'radio' => 
    array (
      0 => 'time',
      1 => '|7200|3600|1800',
      2 => 'cookies有效时间|2小时|1小时|30分钟',
      3 => '',
      4 => '',
      5 => 'N_delete',
      6 => '',
    ),
  ),
  );
 
// 表单提交效验
$past = $_form->postForm($form['login']);
$dd = array('title'=>'标题','categories'=>'类别');
// $dd 为已有的信息(如更新时的信息输出) POST数据位内部处理具有优先权
if(!emptyempty($past))
{
        echo "
"; <br>
        print_r($past); <br>
        echo"
";
}
echo '
';
echo $_form->formHtml($form['login'],$dd);
echo '
';

希望本文所述对大家的PHP程序设计有所帮助。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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