Table of Contents
php form sensitive character filtering class, php form filtering
Home Backend Development PHP Tutorial PHP form sensitive character filtering class, PHP form filtering_PHP tutorial

PHP form sensitive character filtering class, PHP form filtering_PHP tutorial

Jul 13, 2016 am 10:12 AM
php character form filter

php form sensitive character filtering class, php form filtering

The example in this article describes the PHP form sensitive character filtering class and its usage. Share it with everyone for your reference. The specific analysis is as follows:

Copy code The code is as follows:

/**
* Form generation verification file
*/
$_form = new formHtmlFind();
class formHtmlFind{
/**
* Output form function
* $formKey form key
* $infoArray The original information array when updated
                     */

Public function formHtml($array,$infoArray='')
                                                                            // Detect whether the array exists
If(emptyempty($array))return false;
                      $newform = null;
// Information array (update information)
$this->infoArray = !emptyempty($infoArray)?$infoArray:array();
$this->array['class'] = get_class_methods(get_class());
foreach ($array as $key =>$arr)
                                                                            // Convert key value to pure English
                           $key = preg_replace("/[^a-z]/i",'',$key);
// Generate form
$newform .= $this->outputForm($arr,$key);
                                                                                                    // Output form
                         return $newform.$this->jsError();
          }
/**
* Generate form function
                     */
         private function outputForm($arr,$key)
                                                                                                $value = null;
If(emptyempty($arr))return false;
// input Type
$type = $key;
                                  // input NAME
​​​​​​​​                                                                                                                                                                                                          out outps out out out out out way to being's type to be so conveniently like                         $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
                   $style = trim($arr[3]);
If($key!=="hidden")
                                                                            $dt = "
{$title}
";
// js error message
$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); // Multiple selection class
          }
/**
* Submit data for testing
                     */
Public function postForm($array)
                                                                            // Detect whether the array exists
If(emptyempty($array)||emptyempty($_POST))return false;
$this->post = $_POST; $this->array['class'] = get_class_methods(get_class());
foreach ($array as $key =>$arr)
                                                                            // Convert key value to pure English
                           $key = preg_replace("/[^a-z]/i",'',$key);
// Detect logout file form
If (!emptyempty($arr)&&'file' != $key)$newData[trim($arr[0])] = $this->postFind($arr,$key);
                                                                                                    // Output form
If(!emptyempty($this->error))
                                                                                                                                                                    return false;                                                                                                                           else return $newData;
          }
/**
* Generate form
                     */
         private function newInput($type,$name,$value,$style,$title)
                                                                            switch ($type)
                                                                           case 'text':
// Single line of text
Return "";
break;
case 'password':
//Password input
Return "";
break;
case '':
//Multiple lines of text
Return "";
break;
case 'hidden':
                                                                                                                                                                                                                      ​  Return "";
break;
case 'file':
                                                                                                                                                                          Return "";
break;
case 'submit':
                                                                                                                                                                                              Return "";
                                break;
                        default:
                                return "{$type}类型错误!!!";
                                break;
                }
        }
        /**
* Submit information for testing
* Error returns 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                                                                                                                                                                                                                                                                        ​
                                                                                                                                                                                                                                                                                                                                                              $data                                // Output new data
                       return $data;
          }
/**
* Multi-select form generation
                     */
         private function formSelect($type,$name,$value,$title,$style)
                                                                                                 $outform = null;
// Initial
when triggering update and commit actions $nowvalue = (!emptyempty($this->post[$name]))?$this->post[$name]:$this->infoarray[$name];
// Compatible with multi-select recognition, converted to array
If(!emptyempty($nowvalue))$valueArray = explode(",",$nowvalue);
// Option title
If(is_array($title))
                                                                            array_unshift($title,'select');
$titarray = array_values($title);
                        }else $titarray = explode("|",$title);
// Option value
If(is_array($value))
                                                                            array_unshift($value,'select');
$valarray = array_keys($value);
If(emptyempty($title))$titarray = array_values($value);
                                                                                                                            else $valarray = explode("|",$value);
// Cancel the initial default value of the form
If(!emptyempty($this->post)&&!emptyempty($this->infoArray))$value = preg_replace("/Y_/i",'',$value);

foreach ($valarray as $key =>$varl)
                                                                            // Non-default recognition
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("rn"
                                                ,$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);
        }
        /**
* Form validation and all ck_ class functions
                     */
        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;
          }
//----------------------------------------The following detection functions can be called externally
            // Length
          public function lengthDetect($string,$str){
                      $len = split('-',trim($str));
Return (strlen($string) > ($len[0]-1) && strlen($string) < ($len[1]+1))? true:false;
          }
             // Price
          public function moneyDetect($str){
                    return preg_match("/^(-|+)?d+(.d+)?$/",$str);
          }
              // Email
          public function emailDetect($str){
                     return preg_match("/^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/", $str);
          }
// URL
Public function urlDetect($str){
return preg_match("/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*( [^<>"])*$/", $str);
          }
               // Numeric type
          public function numDetect($str){
                      return is_numeric($str);
          }
             // Chinese
          public function cnDetect($str){
                     return preg_match("/^[x7f-xff]+$/", $str);
          }
                                                                                                                                                                                                                                                                                              // Letter
          public function enDetect($str){
                    return preg_match("/^[A-Za-z]+$/", $str);
          }
// Mix of numbers and letters
          public function numenDetect($str){
                   return preg_match("/^([a-zA-Z0-9_-])+$/",$str);
          }
                                          // Phone number
          public function telDetect($str){
                    return ereg("^[+]?[0-9]+([xX-][0-9]+)*$", $str);
          }
// Sensitive words
          public function keyDetect($str){
                    return (!preg_match("/$badkey/i",$str));
          }
//------------------------------------------------ -----Output
// Character replacement
Public function ck_filter($str){
$str=(is_array($str))? implode(",",$str):$str;
                              $str=nl2br($str); //Replace the carriage return with

                    $str=htmlspecialchars($str); //Convert special characters into HTML format.
//$str=str_replace(array(" ",' Return $str;
          }
             // escape
Function ck_escape($str)
                                       {
If (!get_magic_quotes_gpc())return addslashes($str);
                       return $str;
          }
              // MD5 encryption
Public function ck_md5($str){
Return MD5($str);
          }
// base64 encryption
Public function ck_base64($str){
Return base64_encode($str);
          }
             // time
          function ck_time($str){
// time_r() comes in the public function file
If(!is_numeric($str))
                                                                            Return time_r($str);
                                                                                                                            else return $str;
          }
// Conditional cancellation (number)
          public function ck_cancel($str){
Return (!is_numeric($str))? $str:"";
          }
// Unconditional logout
Public function ck_delete(){
                       return null;
          }
// js error message
         private function jsError()
                                       {
If(emptyempty($this->error))return false;
                         return "
& Lt; script language = javascript & gt; rn var error = new array (". Trim ($ this- & gt; error, ',').");
                           rn for (i=0; i < error.length; i++){
                                                                                                                                                                                                                                                                                                                          ";
          }
}

// Demo:
$form[1] =array(
'text'=>array('title','','Product name','size=40','Product name is indispensable!','Y','cn,1-30'),
'text1'=>array('categories','','Product Name','','','Y_base64'),
'select'=>array('superiors','||1|2|Y_3','Product category|Select|1|2|3','','Required option','Y'),
'radio'=>array('superiors1','|1|Y_2|3','product xun|product 1|product 2|product 3','','required option','Y'),
'checkbox'=>array('superiors2',array(1=>'11',2=>'22',3=>'33'),'','','required', 'Y'),
'file'=>array('ddd','','file'),
);
$form =array (
'login' =>
array (
'text' =>
array (
        0 => 'user',
1 => '',
      2 => 'Username',
3 => 'size=20',
4 => '!',
5 => 'Y',
​ 6 => 'numen,6-12',
),
'password' =>
array (
        0 => 'pass',
1 => '',
2 => 'Password',
3 => 'size=22',
         4 => 'Password format is wrong!',
5 => 'Y_md5',
​ 6 => 'numen,6-12',
),
'radio' =>
array (
        0 => 'time',
1 => '|7200|3600|1800',
        2 => 'Cookies validity time|2 hours|1 hour|30 minutes',
3 => '',
4 => '',
5 => 'N_delete',
​ 6 => '',
),
),
);

// Form submission validation
$past = $_form->postForm($form['login']);
$dd = array('title'=>'Title','categories'=>'Category');
// $dd is existing information (such as information output during update). Internal processing of POST data bits has priority
if(!emptyempty($past))
{
echo "
"; <br>
            print_r($past); <br>
echo "
";
}
echo '
';
echo $_form->formHtml($form['login'],$dd);
echo '
';

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/923907.htmlTechArticlephp form sensitive character filtering class, php form filtering This article describes the php form sensitive character filtering class and its usage. Share it with everyone for your reference. The specific analysis is as follows: Copy the code...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

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

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.

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.

See all articles