Home Backend Development PHP Tutorial PHP filter sensitive character class example code

PHP filter sensitive character class example code

Jul 14, 2017 am 10:08 AM
php code Example

The so-called sensitive characters refer to articles that contain unhealthy or reactionary information, information that affects society, and will be regarded as sensitive characters. Because sometimes the sensitive characters entered by the user will invisibly affect the correct execution of the program, the famous database injection attack is to add database control instructions to the query conditions, thereby achieving the attacker's purpose.

This article mainly introduces the PHP form sensitive character filtering class and its usage examples. It analyzes in detail the filtering function for sensitive characters in form generation and submission. It is a very practical skill and is needed. Friends can refer to it. The specific analysis is as follows:

/** 
* 表单生成验证文件 
*/ 
$_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 = "<dt>{$title}</dt><dd>"; 
                        // js错误提示 
                        $dd = "<tt id="J{$name}"></tt></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[&#39;class&#39;] =  get_class_methods(get_class()); 
                foreach ($array as $key =>$arr) 
                { 
                        // 键值转换为纯英文 
                        $key = preg_replace("/[^a-z]/i",&#39;&#39;,$key); 
                        // 检测 注销file类表单 
                        if (!emptyempty($arr)&&&#39;file&#39; != $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 &#39;text&#39;: 
                                // 单行文本 
                                return  "<input type="text" name="{$name}" value="{$value}" {$style}/>"; 
                                break; 
                        case &#39;password&#39;: 
                                //密码输入 
                                return "<input type="password" name="{$name}" {$style}/>"; 
                                break; 
                        case &#39;&#39;: 
                                //多行文本 
                                return "<textarea name="{$name}" {$style}/>{$value}</textarea>"; 
                                break; 
                        case &#39;hidden&#39;: 
                                // 隐藏 
                                return "<input type="hidden" name="{$name}" value="{$value}" {$style}/>"; 
                                break; 
                        case &#39;file&#39;: 
                                // 文件上传 
                                return "<input type= "file"name="{$name}" {$style}/>"; 
                                break; 
                        case &#39;submit&#39;: 
                                // 提交 
                                return "<input type="submit" name="{$name}" value="$value" $style}/>"; 
                                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]))?&#39;ck_&#39;.$KKarray[1]:&#39;&#39;; 
                        // 输出通过检测的合法数据 
                        $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,&#39;选择&#39;); 
                        $titarray = array_values($title); 
                }else $titarray = explode("|",$title); 
                // 选项值 
                if(is_array($value)) 
                { 
                        array_unshift($value,&#39;选择&#39;); 
                        $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",&#39;&#39;,$value); 
 
                foreach ($valarray as $key =>$varl) 
                { 
                        // 非默认的识别 
                        if(!emptyempty($valueArray))$select   = (in_array($varl,$valueArray))?&#39;Y&#39;:&#39;&#39;; 
                        //  判断是否为默认 
                        else $select   = (eregi("Y_",$varl))? &#39;Y&#39;:&#39;&#39;; 
 
                        if($key >&#39;0&#39;) 
                        { 
                                $_title=($titarray[$key])? $titarray[$key]:$title; 
                                switch ($type) 
                                { 
                                        case &#39;select&#39;: 
                                                if(&#39;Y&#39; == $select)$select = &#39;selected&#39;; 
                                                $outform .=        sprintf("<option %s value="%s"/>%s</option>rn" 
                                                ,$select,preg_replace("/Y_/i",&#39;&#39;,$varl),$_title); 
                                                break; 
                                        case &#39;radio&#39;: 
                                                if(&#39;Y&#39; == $select)$select = &#39;checked&#39;; 
                                                $outform .= sprintf("<label>%s<input %s type="radio" name="%s" value="%s" %s/></label>rn", 
                                                $_title,$select,$name,$varl,$style); 
                                                break; 
                                        case &#39;checkbox&#39;: 
                                                if(&#39;Y&#39; == $select)$select = &#39;checked&#39;; 
                                                $outform .= sprintf("<label>%s<input %s type="checkbox" name="%s[]" value="%s" %s/></label>rn",$_title,$select,$name,$varl,$style); 
                                                break; 
                                } 
                                $select =null; 
                        } 
                } 
                // 下拉选择 
                if($type ==&#39;select&#39;)$outform = sprintf(&#39;<select name="%s" %s>%s</select>&#39;,$name,$style,$outform); 
                return sprintf("<dt>%s</dt><dd>%s<tt id="J%s"></tt></dd>rn",$titarray[0],$outform,$name); 
        } 
        /** 
         * 表单验证 及全部 ck_类函数 
         */ 
        private function ck_split($standard,$name,$title,$find,$error) 
        { 
                //  非必填缺省跳过 
                if(eregi(&#39;N&#39;,$find) && emptyempty($this->post[$name]))return false; 
                // 必填缺省检测 
                if(eregi(&#39;Y&#39;,$find) && emptyempty($this->post[$name]))return "["J{$name}","$error"],"; 
                $t_error = null; 
                // 多项检测 
                $arr = explode(&#39;,&#39;,$standard); 
                // POST数据检测 
                if(!emptyempty($arr))foreach ($arr as $var) 
                { 
                        if(trim($var)!=&#39;&#39;) 
                        { 
                                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":&#39;lengthDetect&#39;; 
                if(!in_array($detect,$this->array[&#39;class&#39;])) 
                { 
                        location(&#39;index.php&#39;,$ck,&#39; Lack of function !!!&#39;); 
                } 
                return $detect; 
        } 
        //-------------------------------------以下为检测函数可外部调用 
        // 长度 
        public function lengthDetect($string,$str){ 
                $len = split(&#39;-&#39;,trim($str)); 
                return (strlen($string) > ($len[0]-1) && strlen($string) < ($len[1]+1))? true:false; 
        } 
        // 价格 
        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]+[/=?%-&_~`@[]&#39;:+!]*([^<>"])*$/", $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); //将回车替换为<br> 
                $str=htmlspecialchars($str); //将特殊字元转成 HTML 格式。 
                //$str=str_replace(array(" ",&#39;<? &#39;),array(" ",&#39;< ?&#39;),$str); //替换空格替换为 
                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  " 
                <script  language=javascript> rn var error = new Array(".trim($this->error,&#39;,&#39;)."); 
                        rn for (i=0; i < error.length; i++){ 
                        rn document.getElementById(error[0]).innerHTML=error[1]; 
                         }rn </script> 
                "; 
        } 
} 
 
// 演示: 
$form[1] =array( 
&#39;text&#39;=>array(&#39;title&#39;,&#39;&#39;,&#39;产品名称&#39;,&#39;size=40&#39;,&#39;产品名称不可缺少!&#39;,&#39;Y&#39;,&#39;cn,1-30&#39;), 
&#39;text1&#39;=>array(&#39;categories&#39;,&#39;&#39;,&#39;产品名称&#39;,&#39;&#39;,&#39;&#39;,&#39;Y_base64&#39;), 
&#39;select&#39;=>array(&#39;superiors&#39;,&#39;||1|2|Y_3&#39;,&#39;产品类别|选择|1|2|3&#39;,&#39;&#39;,&#39;必选项&#39;,&#39;Y&#39;), 
&#39;radio&#39;=>array(&#39;superiors1&#39;,&#39;|1|Y_2|3&#39;,&#39;产品xun|产品1|产品2|产品3&#39;,&#39;&#39;,&#39;必选项&#39;,&#39;Y&#39;), 
&#39;checkbox&#39;=>array(&#39;superiors2&#39;,array(1=>&#39;11&#39;,2=>&#39;22&#39;,3=>&#39;33&#39;),&#39;&#39;,&#39;&#39;,&#39;必选项&#39;,&#39;Y&#39;), 
&#39;file&#39;=>array(&#39;ddd&#39;,&#39;&#39;,&#39;文件&#39;), 
); 
$form =array ( 
  &#39;login&#39; =>  
  array ( 
    &#39;text&#39; =>  
    array ( 
      0 => &#39;user&#39;, 
      1 => &#39;&#39;, 
      2 => &#39;用户名&#39;, 
      3 => &#39;size=20&#39;, 
      4 => &#39;!&#39;, 
      5 => &#39;Y&#39;, 
      6 => &#39;numen,6-12&#39;, 
    ), 
    &#39;password&#39; =>  
    array ( 
      0 => &#39;pass&#39;, 
      1 => &#39;&#39;, 
      2 => &#39;密 码&#39;, 
      3 => &#39;size=22&#39;, 
      4 => &#39;密码格式错误!&#39;, 
      5 => &#39;Y_md5&#39;, 
      6 => &#39;numen,6-12&#39;, 
    ), 
    &#39;radio&#39; =>  
    array ( 
      0 => &#39;time&#39;, 
      1 => &#39;|7200|3600|1800&#39;, 
      2 => &#39;cookies有效时间|2小时|1小时|30分钟&#39;, 
      3 => &#39;&#39;, 
      4 => &#39;&#39;, 
      5 => &#39;N_delete&#39;, 
      6 => &#39;&#39;, 
    ), 
  ), 
  ); 
 
// 表单提交效验 
$past = $_form->postForm($form[&#39;login&#39;]); 
$dd = array(&#39;title&#39;=>&#39;标题&#39;,&#39;categories&#39;=>&#39;类别&#39;); 
// $dd 为已有的信息(如更新时的信息输出) POST数据位内部处理具有优先权
if(!emptyempty($past)) 
{ 
        echo "<pre class="brush:php;toolbar:false">"; 
        print_r($past); 
        echo"
"; } echo '
'; echo $_form->formHtml($form['login'],$dd); echo '
';
Copy after login

The above is the detailed content of PHP filter sensitive character class example code. For more information, please follow other related articles on the PHP Chinese website!

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
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles