PHP Filter Sensitive character class instance code

Source: Internet
Author: User
Tags php form
The so-called sensitive character refers to: In the article contains unhealthy or reactionary information, the impact of social information, will be considered sensitive characters. Because sometimes the user input sensitive characters will affect the correct execution of the program, the famous database injection attack is to add the database control commands in the query conditions, so as to achieve the purpose of the attackers.

This article mainly introduces the PHP form sensitive character filter class and its usage examples, detailed analysis of form generation and submission, and other aspects of the filtering function for sensitive characters, is a very practical skill, the need for friends can refer to the following, specific analysis as follows:

/** * Form Generated validation file */$_form = new Formhtmlfind ();          Class formhtmlfind{/** * Output form function * $formKey form key * $infoArray The original array of information when updating * * Public Function formhtml ($array, $infoArray = ") {//detects if an 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) {//Key value converted to plain english $key = pr                         Eg_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]); The input initial value does not contain multiple selections, the single 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 prompt $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);                 Multi-Select Class}/** * Submit data detection */Public Function Postform ($array) { Detects if an 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) {//Key value converted to plain english $key = pr                         Eg_replace ("/[^a-z]/i", ", $key); Detect unregister File Class form if (!emptyempty ($arr) && ' file '! = $key) $newData [Trim ($arr [0])] = $this                 Postfind ($arr, $key); }//Output form if (!emptyempty ($this->error)) {retur                 n false;         } else return $newData;    }         /**      * Generate form */Private Function Newinput ($type, $name, $value, $style, $title) {SWI                                 TCH ($type) {case ' text '://single line of 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} ' {$styl                                 e}/>{$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         }}/** * Commit information detection * error returned errors */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 Tip $error = Trim ($arr [4]);                 Detection type Y N $find = Trim ($arr [5]);                 Inspection standard $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 conversion $KKarray = array (); if (Preg_match ("/y|                         N/is ", $find)) {$KKarray = Split (" _ ", $find); Escape or filter $escape _filter = (!emptyempty ($KKarray [1]))? '                         Ck_ '. $KKarray [1]: '; $data = ($escape _filter) of legitimate data passed by the output $this, $escape _filter ($this->post[$name]): $                  this->post[$name];           }      else $data = "";         Outputs a new data return $data;         }/** * Multi-Select Class form generation */Private Function Formselect ($type, $name, $value, $title, $style)                 {$outform = null; Initial $nowvalue when triggering an update and commit action = (!emptyempty ($this->post[$name])? $this->post[$name]: $this->infoarra                 y[$name];                 Compatible with multi-select recognition, 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); Cancels the initial default value of the form if (!emptyempty ($this->post) &&!emptyempty ($this->infoarray) $value = Preg_repla                  CE ("/y_/i", ", $value); foreach ($valarray as $key = + $varl) {//non-default recognition if (!emp Tyempty ($valueArray)) $select = (In_array ($varl, $valueArray))? '                         Y ': '; Determine if the default else $select = (eregi ("Y_", $varl))?                          ' Y ': '; if ($key > ' 0 ') {$_title= ($titarray [$key])? $titarray [$key]: $tit                                 Le                                                 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; }}//drop-down Select if ($type = = ' SELECT ') $outform = sprintf (' <select name= "%s"%                 S>%s</select> ', $name, $style, $outform); Return sprintf ("<dt>%s</dt><dd>%s<tt id=" j%s "></tt></dd>rn", $titarray [0],$         Outform, $name); }/** * Form validation and All Ck_ class functions */Private Function Ck_split ($standard, $name, $title, $find, $error ) {//non-mandatory default skip if (eregi (' N ', $find) && emptyempty ($this->post[$name]) r                 Eturn false; Required default detection if (eregi (' Y ', $find) && emptyempty ($this->post[$name])) return "[" j{$name} "," $error "],"                 ;                 $t _error = null;             Multiple detection $arr = explode (', ', $standard);    The Post data detects if (!emptyempty ($arr)) foreach ($arr as $var) {if (t                                 RIM ($var)! = ") {switch ($this->post)                                                 {Case Is_array ($this->post[$name]):                                                 Detection of array classes foreach ($this->post[$name] as $_var) {$t _error.= ($this->ck_o                                                         Pen ($_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 determine 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 detection function 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); }//Mail 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);         }//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); }//alphanumeric mixed 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 word public Function Keydetect ($STR) {return (!preg_match ("/$badkey/I", $str)); }//-----------------------------------------------------output//character replacement public function ck_filter ($s                 TR) {$str = (Is_array ($STR))? Implode (",", $str): $str; $str =nl2br ($STR); Replace the carriage return with the <br> $str =htmlspecialchars ($STR);                 Converts special characters to HTML format. $str =str_replace (Array ("", ' <? '), Array ("", ' <? '), $STR);         Replace the space with the return $str; }//Escape function Ck_escape ($STR) {if (!GET_MAGIC_QUOTES_GPC ()) return Addslashes ($                 STR);         return $str;      }//MD5 encrypt public Function ck_md5 ($STR) {           Return MD5 ($STR);         }//Base64 encrypt public Function ck_base64 ($STR) {return base64_encode ($STR);                  }//Time function Ck_time ($STR) {//Time_r () to the common function file if (!is_numeric ($STR))                 {return Time_r ($STR);         } else return $str;         }//Conditional logoff (number) public function Ck_cancel ($STR) {return (!is_numeric ($STR))? $str: "";         }//Unconditionally unregister public Function Ck_delete () {return null; }//JS error hint Private function Jserror () {if (Emptyempty ($this->error)) return FAL                 Se                         Return "<script language=javascript> rn var error = new Array (". Trim ($this->error, ', '). "); RN for (i=0; i < error.length; i++) {rn document.getElementById (error[0]). innerhtml=error[1];         }rn </script> "; }}//Demo: $form [1] =array (' Text ' =>array (' title ', ' ', ' Product name ', ' size=40 ', ' Product name 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=> ' one ',2=> ' ',3=> ') 33 '), ' ', ' ', ' required option ', ' Y ', ' File ' =>array (' ddd ', ' ', ' files '); $form =array (' login ' = = Array (' text ' = = = Array (0 = ' user ', 1 = ', 2 =& Gt ' username ', 3 = ' size=20 ', 4 = '! ', 5 = ' Y ', 6 = ' numen,6-12 ', ' Password ' =&      Gt       Array (0 = ' pass ', 1 = ', 2 = ' password ', 3 = ' size=22 ', 4 = ' Password format error! '), 5 = ' Y_md5 ', 6 = ' numen,6-12 ',), ' radio ' = = array(0 = ' time ', 1 = ' |7200|3600|1800 ', 2 = ' cookies are valid for hours------hours, |30 minutes ', 3 = ',  4 = ", 5 = ' N_delete ', 6 =",),); form submission Validation $past = $_form->postform ($form [' Login ']); $DD = Array (' title ' = ' + ' headline ', ' categories ' = ' category ');         $dd The post data bit internal processing has priority if (!emptyempty ($past)) {echo "<pre>" For information that is already present (such as information output at update);         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> ";
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.