我正在寻找使用PHP构建HTML表单,但我想知道可能已经存在库。 你知道我可以使用的任何开源库吗?
你认为,创建函数来使用 php 构建 HTML 表单是个好主意吗? 性能是否有任何风险(加载我的网站的页面)?
function input($label,$id,$type)
{
echo $label.' <input type="'.$type.'" id="'.$id.'" name="'.$id.'" />';
}
input('User name','login','text');
我的目的是构建一个库来快速编写代码。
我有几个当年创建的函数。我将它们用于不依赖于框架的项目。现在,如果可能的话,我更喜欢使用Symfony的Form组件。
看看,它会给你一个想法。
function lb($text, $forid='', $style='', $attr='')
{
if($style!='')
$style='style="'.$style.'"';
if($forid!='')
$forid='for="'.$forid.'"';
return '<label '.$style.$forid.' '.$attr.'>'.$text.'</label>';
}
//generates input field, and populates inputs. Good for edit forms too.
function in($name, $cust_val='', $style='', $attr='', $set_id=true)
{
global $edit;
$val='';
if(isset($edit[$name]))
$val=$edit[$name];
if($cust_val!='')
{
$val=$cust_val;
}
if($style!='')
$style='style="'.$style.'"';
$setid='';
if($set_id)
$setid="id='"".$name."'"";
return '<input type="text" name="'.$name.'" '.$setid.' '.$attr.' '.$style.' value="'.ht($val).'">';
}
/*
* Prints multiple <td></td> for a table structure
*
* @param array vals - values to be used inside tds
* @param boolean encloseInTR when true puts <tr> outside tds
*/
function tds($vals, $encloseInTR=false)
{
$out='';
foreach($vals as $v)
{
$out.='<td>'.$v.'</td>';
}
if($encloseInTR)
$out = '<tr>'.$out.'</tr>';
return $out;
}
/*
* Prints multiple <th></th> for a table structure
*
* @param array vals - values to be used inside ths
* @param boolean $encloseInTHEAD when true puts <thead> outside th
* @param class class var to be added to th
*/
function ths($vals, $encloseInTHEAD=false, $class='')
{
$out='';
foreach($vals as $v)
{
if($class!='')
$out.='<th class="'.$class.'">'.$v.'</th>';
else
$out.='<th>'.$v.'</th>';
}
if($encloseInTHEAD)
$out = '<thead>'.$out.'</thead>';
return $out;
}
//alias htmlspecialchars
function ht($string)
{
return htmlspecialchars($string,ENT_QUOTES);
}
这就是我的表单代码的样子:
$form =
form_start(..)
.lb('First name','')
.in('name','','width:400px;')
.lb('Telefon','').cl()
.in('tel','','width:400px;')
//...
.form_end()
;
性能没有风险,因为你正在做的事情基本上是PHP框架中所有FormBuilder类已经做的事情。我唯一建议的是对您的输入进行HTML清理,特别是:
function input($label,$id,$type)
{
echo htmlspecialchars($label).' <input type="'.htmlspecialchars($type, ENT_QUOTES).'" id="'.htmlspecialchars($id, ENT_QUOTES).'" name="'.htmlspecialchars($id, ENT_QUOTES).'" />';
}
input('User name','login','text');
这是为了避免可能的 XSS 攻击、代码注入和视图问题。