SoFunction
Updated on 2025-03-02

PHP form sensitive character filtering class


/**
* 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
                $name   = trim($arr[0]);
// input initial value does not contain multiple choice, single choice class
                $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 = "<dt>{$title}</dt><dd>";
// js error message
                        $dd = "<tt ></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); // Multiple-select class
        }
        /**
* Submit data detection
         */
        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);
// Detection Logout file type 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 text
                                return  "<input type="text" name="{$name}" value="{$value}" {$style}/>";
                                break;
                        case 'password':
//Password input
                                return "<input type="password" name="{$name}" {$style}/>";
                                break;
                        case '':
//Multiple lines of text
                                return "<textarea name="{$name}" {$style}/>{$value}</textarea>";
                                break;
                        case 'hidden':
// Hide
                                return "<input type="hidden" name="{$name}" value="{$value}" {$style}/>";
                                break;
                        case 'file':
// File upload
                                return "<input type= "file"name="{$name}" {$style}/>";
                                break;
                        case 'submit':
// submit
                                return "<input type="submit" name="{$name}" value="$value" $style}/>";
                                break;
                        default:
return "{$type} type error!!!";
                                break;
                }
        }
        /**
* Submit information detection
* 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 message
                $error    = trim($arr[4]);
// Detection type Y N
                $find     = trim($arr[5]);
// Testing standards
                $standard = trim($arr[6]);
                //
                if(!emptyempty($standard))$this->error .=$this->ck_split($standard,$name,$title,$find,$error);
// Convert to string
                if(is_array($this->post[$name]))$this->post[$name] = implode(",",$this->post[$name]);
// Escape or other transformation
                $KKarray = array();
                if(preg_match("/Y|N/is",$find))
                {
                        $KKarray       = split("_", $find);
// Escape or filter
                        $escape_filter = (!emptyempty($KKarray[1]))?'ck_'.$KKarray[1]:'';
// Output legal data that passes detection
                        $data          = ($escape_filter)?$this->$escape_filter($this->post[$name]):$this->post[$name];
 
                }
                else  $data        = "";
// Output new data
                return $data;
        }
        /**
* Multiple-select form generation
         */
        private function formSelect($type,$name,$value,$title,$style)
        {
                $outform = null;
// The initial time when the update and submission action is triggered
                $nowvalue = (!emptyempty($this->post[$name]))?$this->post[$name]:$this->infoarray[$name];
// Compatible with multiple selection 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 identification
                        if(!emptyempty($valueArray))$select   = (in_array($varl,$valueArray))?'Y':'';
// Determine whether it is the default
                        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("<option %s value="%s"/>%s</option>rn"
                                                ,$select,preg_replace("/Y_/i",'',$varl),$_title);
                                                break;
                                        case 'radio':
                                                if('Y' == $select)$select = 'checked';
                                                $outform .= sprintf("<label>%s<input %s type="radio" name="%s" value="%s" %s/></label>rn",
                                                $_title,$select,$name,$varl,$style);
                                                break;
                                        case 'checkbox':
                                                if('Y' == $select)$select = 'checked';
                                                $outform .= sprintf("<label>%s<input %s type="checkbox" name="%s[]" value="%s" %s/></label>rn",$_title,$select,$name,$varl,$style);
                                                break;
                                }
                                $select =null;
                        }
                }
// Pull down to select
                if($type =='select')$outform = sprintf('<select name="%s" %s>%s</select>',$name,$style,$outform);
                return sprintf("<dt>%s</dt><dd>%s<tt ></tt></dd>rn",$titarray[0],$outform,$name);
        }
        /**
* Form verification and all ck_class functions
         */
        private function ck_split($standard,$name,$title,$find,$error)
        {
// Non-required default skip
                if(eregi('N',$find) && emptyempty($this->post[$name]))return false;
// Required default detection
                if(eregi('Y',$find) && emptyempty($this->post[$name]))return "["J{$name}","$error"],";
                $t_error = null;
// Multiple tests
                $arr = explode(',',$standard);
// POST data detection
                if(!emptyempty($arr))foreach ($arr as $var)
                {
                        if(trim($var)!='')
                        {
                                switch ($this->post)
                                {
                                        case is_array($this->post[$name]):
// Detection of array class
                                                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"],":"";
        }
// Function call
        private function ck_open($string,$str)
        {
                $functi = $this->ck_detected($str);
                return ($this->$functi($string,$str))? true:false;
        }
// Type judgment
        private function ck_detected($str)
        {
                $detect = (eregi("^[a-zA-Z]*$",$str))? "{$str}Detect":'lengthDetect';
                if(!in_array($detect,$this->array['class']))
                {
                        location('',$ck,' Lack of function !!!');
                }
                return $detect;
        }
//-----------------------------------------------------------------------------------------------------------------------------
// 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);
        }
// mail
        public function emailDetect($str){
                return preg_match("/^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/", $str);
        }
// Website
        public function urlDetect($str){
                return preg_match("/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*([^<>"])*$/", $str);
        }
// Digital
        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);
        }
// telephone 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));
        }
//-----------------------------------------------------------------------------------------------------------------------------
// Character replacement
        public function ck_filter($str){
                $str=(is_array($str))? implode(",",$str):$str;
$str=nl2br($str); //Replace Enter with <br>
$str=htmlspecialchars($str); //Convert special characters to HTML format.
//$str=str_replace(array(" ",'<? '),array(" ",'< ?'),$str); //Replace space with
                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 (digital)
        public function ck_cancel($str){
                return (!is_numeric($str))? $str:"";
        }
// Unconditional cancellation
        public function ck_delete(){
                return null;
        }
// js error message
        private function jsError()
        {
                if(emptyempty($this->error))return false;
                return  "
                <script  language=javascript> rn var error = new Array(".trim($this->error,',').");
                        rn for (i=0; i < ; i++){
                        rn (error[0]).innerHTML=error[1];
                         }rn </script>
                ";
        }
}
 
// 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 Option','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 valid 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'=>'categories');
// $dd is the existing information (such as the information output during update) POST data bit internal processing has priority
if(!emptyempty($past))
{
        echo "<pre>";
        print_r($past);
        echo"</pre>";
}
echo '<form method="POST" NAME="PostTopic" action="" enctype="multipart/form-data" style="margin:0px;">';
echo $_form->formHtml($form['login'],$dd);
echo '<input type="submit" value="Y" name="B1"></form>';