<!DOCTYPE HTML> <html> <head> <title>form</title> <style type="text/css"> .err{ color: red; } </style> </head> <body> <?php $name = $email = $website = $commet = $gender = $nameErr = $emailErr = $genderErr = ''; if($_SERVER['REQUEST_METHOD'] == "POST"){ if(empty($_POST['name'])){ $nameErr = "姓名为必填项"; }else{ $name = test_input($_POST['name']); if(!preg_match("/^[a-zA-Z ]*$/" , $name)){ $nameErr = "姓名只允许字母和空格"; } } if(empty($_POST['email'])){ $emailErr = "邮件为必填项"; }else{ $email = test_input($_POST['email']); if(!preg_match("/([w-]+@[w-]+.[w-]+)/" , $email)){ $emailErr = "邮件格式不正确"; } } if(empty($_POST['gender'])){ $genderErr = "性别为必选项"; }else{ $gender = test_input($_POST['gender']); } $website = empty($_POST['website'])?'':test_input($_POST['website']); $commet = empty($_POST['commet'])?'':test_input($_POST['commet']); } function test_input($str){ $str = trim($str); $str = stripslashes($str); $str = htmlspecialchars($str); return $str; } ?> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"> <p>姓名:<input type="text" name="name" value="<?php echo $name;?>"/><span class="err">* <?php echo $nameErr; ?> </span></p> <p>邮件:<input type="text" name="email" value="<?php echo $email;?>" /><span class="err">* <?php echo $emailErr; ?></span></p> <p>网址:<input type="text" name="website" value="<?php echo $website;?>"/></p> <p>评论:<textarea name="commet" id="" cols="30" rows="10"><?php echo $commet;?></textarea></p> <p>性别 <label><input type="radio" name="gender" value="female" <?php if(isset($gender) && $gender=="female") echo 'checked'; ?>/>女性</label> <label><input type="radio" name="gender" value="male" <?php if(isset($gender) && $gender == 'male') echo 'checked'?>/>男性</label> <span class="err">* <?php echo $genderErr; ?></span> </p> <button>提交</button> </form> <hr /> <?php echo $name;?> <br /> <?php echo $email;?> <br /> <?php echo $website;?> <br /> <?php echo $commet;?> <br /> <?php echo $gender;?> </body> </html> <?php ?>