加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php 在当前页验证表单数据的简单示例

发布时间:2020-05-25 04:58:21 所属栏目:PHP 来源:互联网
导读:php 在当前页验证表单数据的简单示例

感兴趣的小伙伴,下面一起跟随脚本之家 jb51.cc的小编来看看吧。
经测试代码如下:


<?php
/**
 * 验证表单数据
 *
 * @param 
 * @arrange (512.笔记) jb51.cc
 **/
function VerifyForm(&$values,&$errors)
{
// Do all necessary form verification

if (strlen($values['name']) < 3)
$errors['name'] = 'Name too short';
elseif (strlen($values['name']) > 50)
$errors['name'] = 'Name too long';

// Needs better checking ;)
if (!ereg('.*@.*..{2,4}',$values['email']))
$errors['email'] = 'Email address invalid';

if (strlen($values['text']) == 0)
$errors['text'] = 'Text required';

return (count($errors) == 0);
}

function DisplayForm($values,$errors)
{
?>
<html>
<head>
<title>Yadda yadda</title>
<style>
TD.error
{
color: red;
font-weight: bold;
}
</style>
</head>
<body>

<?php
if (count($errors) > 0)
echo "<p>There were some errors in your submitted form,please correct them and try again.</p>";
?>

<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<table>
<tr>
<td>Name:</td>
<td><input type="text" size="30" name="name" value="<?= htmlentities($values['name']) ?>"/>
<td class="error"><?= $errors['name'] ?></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" size="30" name="email" value="<?= htmlentities($values['email']) ?>"/>
<td class="error"><?= $errors['email'] ?></td>
</tr>
<tr>
<td valign="top">Text:</td>
<td>
<textarea name="text" cols="30" rows="6"><?= htmlentities($values['text']) ?></textarea>
</td>
<td class="error"><?= $errors['text'] ?></td>
</tr>
<tr><td colspan="2" align="center"><input type="submit" value="Submit"></tr>
</table>
</form>

</body>
</html>
<?php
}

function ProcessForm($values)
{
mail('foo@bar.com','Form test',$values['text'],"From: "{$values['name']}" <{$values['email']}>");

// Replace with actual page or redirect :P
echo "<html><head><title>Thank you!</title></head><body>Thank you!</body></html>";
}

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$formValues = $_POST;
$formErrors = array();

if (!VerifyForm($formValues,$formErrors))
DisplayForm($formValues,$formErrors);
else
ProcessForm($formValues);
}
else
DisplayForm(null,null);


/*** 来自:脚本之家 jb51.cc(jb51.cc) ***/ 
?>

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读