+ -
当前位置:首页 → 问答吧 → 再次修正表单生产和验证类,支持表单默认选项和更多功能

再次修正表单生产和验证类,支持表单默认选项和更多功能

时间:2009-03-05

来源:互联网

<?php
header("Content-Type: text/html; charset=Utf-8");
/*----------------------------------------------------------------------#
# 表单验证过滤检测类
# 技术支持:http://www.biz-m.com
# 表单范例:
#$formarray =  array('表单类型' => array('键值','初始值','检测标准','名称标题','错误提示语句','样式','检测',......'),);
# 说明:
# 缺省忽略  N
# 必填检测, Y
# 转义输出      _escape
# 过滤输出      _filter
# 注销无输出    _cancel (为数字时被注销)
# 注销无输出    _nooutput (无条件注销)
# 加密输出      _md
# 输出 类型 Into  Update
# 数字类 num 全中文 cn 英文字母 en 金额 money 网址 url 邮箱 email 电话 tel
# 组合(密码类) pass 字节限制 0-99999999 数字字母 numen 铭感词检测 key
# 铭感词过滤之词库
# $badkey ="王八蛋|去死";
#------------------------------------------------------------------------*/
class form_post{
public $array= array();
# $type;  缺省为生产表单  否则输出效验和转义的合法数组;
# $action 表单form头
public function html_form($array,$action="",$type="")
{
  $this->array['class'] =  get_class_methods(get_class());
  if(!is_array($array))return false;
  $outform="";
  foreach ($array as $key => $var){
   $arr ="";
   $key = preg_replace("/[^a-z]/i",'',$key); #键值转换为纯英文
   $arr = $var;
   if($type=="") # 生产表单
   {
    $outform .= (!preg_match("/checkbox|select|radio/i",$key))?
    sprintf('<dt>%s</dt><dd>',trim($arr[3])).
    $this->form_to('form_'.$key,
    trim($arr[3]),
    trim($arr[0]),
    trim($arr[1]),
    trim($arr[5])).
    sprintf("<q id=\"J%s\"></q></dd> \r\n",trim($arr[0])):
    $this->form_go($key,
    trim($arr[3]),
    trim($arr[0]),
    trim($arr[1]),
    trim($arr[5]));
   }
   else #表单验证
   {
    $error .= (count($arr)>6)?
    $this->ck_split(array_slice($arr,6,count($arr)),
    trim($arr[0]),
    trim($arr[2]),
    trim($arr[3]),
    trim($arr[4])):""; # 检测
    if(preg_match("/Y|N/is",$arr[2]))
    {
     $KKarray="";
     $KKarray = split("_", $arr[2]);
     $escape_filter = ($KKarray[1])? 'ck_'.$KKarray[1]:"";# 需要转义和过滤
     $data = ($escape_filter)?
     $this->$escape_filter($_POST[$arr[0]]):
     $_POST[$arr[0]]; # 输出合法数据
     if($data)
     {
      if(is_array($data))$data = implode(",",$data);
      $_data[$arr[0]] = $data;
     }
    }
   }
  }
  # 输出数据
  if(empty($error))
  $data =($type ==="")? $outform :$_data;
  else  $data =$error;
  return $data = (empty($error))? $data : $error;
}
// 生成表单 函数: form_to form_go 及全部 form_类函数
private function form_to($f_type,$title,$name,$value,$more=""){
  if(!in_array($f_type,$this->array['class'])){
   echo $f_type," 函数未包含在本类中,错误!!!";
   exit();
  }
  return $this->$f_type($title,$name,$value,$more);
}
private function  form_go($key,$title,$name,$value,$more=""){
  $valarray = explode("|",$value);
  $titarray = explode("|",$title);
  $rn = count($valarray);
  $min ="";
  $min = ($rn>1)?1:0; //只有一个对话框
  for($i=$min;$i<$rn;$i++)
  {
   $_title="";
   $_title=($titarray[$i])? $titarray[$i]:$title;
   if($key!=='select')
   $outform .= $this->form_to('form_'.$key,$_title,$name,$valarray[$i]);
   else{
   $ss = "";
   $select ="";
   if(eregi("Y_",$valarray[$i]))$select = 'selected'; # 判断是否为默认
   $ss = preg_replace("/Y_/i",'',$valarray[$i]);
   $outform .= sprintf("<option $select  value=\"%s\">%s</option> \r\n",$ss,$_title);
   }
  }
  if($key==='select')$outform = sprintf('<select name="%s" %s>%s</select>',$name,$more,$outform);
  return sprintf("<dt>%s</dt><dd>%s<q id=J%s></q></dd>\r\n",$titarray[0],$outform,$name);
}
//表单验证 及全部 ck_类函数
private function ck_split($str,$name,$type,$title,$_error){
  if(eregi('N',trim($type))&& $_POST[$name])
  return false;
  $t_error ="";
  foreach ($str as $i=> $var)
  {
   if(trim($var)!=="")
   {
    if(is_array($_POST[$name])) # 数组类的检测
    {
     foreach ($_POST[$name] as $_var)
     {
      $t_error.= ($this->ck_open($_var,trim($var)))?"":$_error;
      if($t_error)break;
     }
    }
    else
    {
     $t_error.= ($this->ck_open($_POST[$name],trim($var)))?"":$_error;
     if($t_error)break;
    }
   }
  }
  return ($t_error)? "\"J{$name},$t_error\"":"";
}
# 单行文本
public function form_text($title,$name,$value,$more){
  return sprintf('<input type="text" name="%s"  %s  value="%s">',$name,$more,$value);
}
# 密码输入
public function form_password($title,$name,$value,$more){
  return sprintf('<input type="password" name="%s"  %s  value="%s">',$name,$more,$value);
}
# 多选
function form_checkbox($title,$name,$value,$more){
  if(eregi("Y_",$value))$select = 'checked'; # 判断是否为默认
  $value = preg_replace("/Y_/i",'',$value);
  return sprintf("%s<input $select type=\"checkbox\" name=\"%s[]\"  %s  value=\"%s\">",$title,$name,$more,$value);
}
# 多行文本
public function form_textarea($title,$name,$value,$more){
  return sprintf('<textarea name="%s" %s>%s</textarea>',$name,$more,$value);
}
# 隐藏
public function form_hidden($title,$name,$value,$more){
  return sprintf('<input type="hidden" name="%s" value="%s">',$name,$value);
}
# 单选
public function form_radio($title,$name,$value,$more){
  if(eregi("Y_",$value))$select = 'checked'; # 判断是否为默认
  $value = preg_replace("/Y_/i",'',$value);
  return sprintf("%s<input $select type=\"radio\" name=\"%s\" value=\"%s\">",$title,$name,$value);
}
# 文件上传
public function form_file($title,$name,$value,$more){
  return sprintf('<input type="file" name="%s" value="%s">',$title,$name,$value);
}
# 提交
public function form_submit($title,$name,$value,$more){
  return sprintf('<input type="submit" name="%s" value="%s">',$name,$value);
}
# 函数调用
public function ck_open($string,$str){
  $functi = $this->ck_detected($str);
  return ($this->$functi($string,$str))? true:false;
}
# 类型判断
public function ck_detected($str){
  $ck = (eregi("^[a-zA-Z]*$",$str))? 'ck_'.$str:'ck_Length';
  if(!in_array($ck,$this->array['class'])){
   echo $ck," 检测函数未包含在本类中,错误!!!";
   exit();
  }
  return $ck;
}
//-------------------------------------以下为检测函数
# 长度
public function ck_Length($string,$str){
  $len = split('-',trim($str));
  return (strlen($string) > ($len[0]-1) && strlen($string) < ($len[1]+1))? true:false;
}
# 价格
public function ck_money($str){
  return preg_match("/^(-|\+)?\d+(\.\d+)?$/",$str);
}
# 邮件
public function ck_email($str){
  return preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $str);
}
# 网址
public function ck_url($str){
  return preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $str);
}
# 数字型
public function ck_num($str){
  return is_numeric($str);
}
# 中文
public function ck_cn($str){
  return preg_match("/^[\x7f-\xff]+$/", $str);
}
# 字母
public function ck_en($str){
  return preg_match("/^[A-Za-z]+$/", $str);
}
# 数字字母混合
public function ck_numen($str){
  return preg_match("/^([a-zA-Z0-9_-])+$/",$str);
}
# 电话号码
public function ck_tel($str){
  return ereg("^[+]?[0-9]+([xX-][0-9]+)*$", $str);
}
# 敏感词
public function ck_key($str){
  Global $badkey;
  return (!preg_match("/$badkey/i",$str));
}
#-----------------------------------------------------输出
# 字符替换
public function ck_filter($str){
  $str=(is_array($str))? implode(",",$str):$str;
  $str=HTMLSpecialChars($str); //将特殊字元转成 HTML 格式。
  $str=nl2br($str); //将回车替换为<br>
  $str=str_replace(array(" ",'<? '),array(" ",'< ?'),$str); //替换空格替换为
  return $str;
}
# MD5加密
public function ck_md($str){
  return  MD5($str);
}
# 转义
function ck_escape($str){
  $str = is_array($str) ? array_map('addslashes_deep', $str) : addslashes($str);
  return $str;
}
# 有条件注销(数字)
public function ck_cancel($str){
  return (!is_numeric($str))? $str:"";
}
# 无条件注销(数字)
public function ck_delete(){
  return null;
}
}
//---------------------------------------------以下为使用范例
# '表单类型' => array('键值','初始值','检测标准','名称标题','错误提示语句','样式','检测',......',
# 多选,下来菜单和单选使用Y_ 设定初始值
$dd ='键值初始值检测标准名称标题错,,,,,,误提示语句样式检测......';
$formarray = array(
'text'=>array('name','asdfasdfasdf','N','我是text标题','必须填写','size="20" style="border:1px solid #f00;" autocomplete="off"','num'),
'text1'=>array('name0','asdfasdfsdaf','N','我是text1标题','错误提示必须填写','我是样式','num'),
'text2'=>array('name1','sadfsadfsdf','N','我是text2标题','必须填写','onblur="show()" size="20" title="123456"','num',),
'select'=>array('set','0|1|2|Y_3|4|5','N','下拉选择|中国|美国|英国|德国|月球','必须填写','title="123456"','num'),
'checkbox'=>array('box','0|Y_1|2|3|4|5','N','多选|中国|美国|英国|德国|月球,必须填写','title="123456"','num'),
'radio'=>array('radio','0|1|2|3|Y_4|5','N','单选|中国|美国|英国|德国|月球','必须填写','','num'),
'file'=>array('files','','','选择文件'),
'textarea'=>array('texta',$dd,'Y','多行对话'),
'submit'=>array('b','提交表单'),
);
$_form = new form_post();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function show(){
alert("我是鼠标样式,感觉如何?");
}
</script>
<style>
dl {
width: 99%;
clear:both;
line-height: 1.5em;
margin-top: 15px;
padding-top:20px;
}
dt
{
float: left;
width: 25%;
text-align:right;
font-weight:bold;
margin: 1px;
padding: 2px 10px 2px 0;
}
dd
{
float: left;
text-align:left;
letter-spacing:1pt;
FONT-SIZE: 10pt;
width: 70%;
margin: 1px;
padding: 2px;
}
</style>
</HEAD>
<body>
<?php
if($_POST)
{
$post_data = $_form->html_form($formarray,$action,"1");
if(is_array($post_data))
{
  echo "<pre>";
  print_r($post_data);
  echo "</pre>";
}
else echo $post_data;
}
echo '<form action="" method="post">'.$_form->html_form($formarray,$action);
?>
</body>

作者: cyhchenz   发布时间: 2009-03-05

谢谢学习

作者: zxe   发布时间: 2009-03-06

格式整理下,这样看着很累!

作者: lijie250   发布时间: 2009-03-07

作者: cyhchenz   发布时间: 2009-03-08

学习!谢谢!

作者: zxe   发布时间: 2009-05-13