PHP表单验证实例

2018-09-22  本文已影响17人  九尾74
效果图

大致逻辑:

1.通过关键词获取表单信息。 

2.判断表单,信息是否为空。

3.判断格式是否正确 。

4.输出填写的信息。

实现代码

<!DOCTYPE html>

<html lang="zh-cn">

<head>

<meta charset="UTF-8">

<title>个人资料表</title>

</head>

<style>

body

    {

background:url("bdbg.jpg");

background-size:100%100%;

background-repeat:no-repeat;

}

</style>

<body>

  ///定义相关变量

  $name=$eamil=$weburl=$other=$sex=$nameeor=$emaileor=$weburleor=$othereor=$sexeor="";

  if ($_SERVER["REQUEST_METHOD"]=="POST")

{

      ///判断名字是否符合格式

    if (empty($_POST["name"]))

{

        $nameeor="名字是必须字段";

}

    else

        {

            $name=test_input($_POST["name"]);

            if (!preg_match("/^[a-zA-Z ]*$/",$name))

{

                $nameeor="名字不包含空格,字母";

}

}

        ////判断email是否符合格式

        if (empty($_POST["email"]))

{

            $emaileor="email地址不允许为空";

}

        else

            {

                $eamil=test_input($_POST["email"]);

                if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$eamil))

{

                    $emaileor="email地址中格式存在错误,请重试";

}

}

  // 检测 URL 地址是否合法

  if (empty($_POST["weburl"]))

{

      $weburleor = "url是必须的字段";

}

  else

      {

          $weburl = test_input($_POST["weburl"]);

          if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$weburl))

{

          $weburleor = "非法的 URL 的地址";

}

}

  // 检测 备注 是否合法

  if (empty($_POST["other"]))

{

      $othereor = "";

}

  else

  {

      $other=test_input($_POST["other"]);

}

// 检测 备注 地址是否合法

  if (empty($_POST["sex"]))

{

      $sexeor = "性别是必须的";

}

  else

  {

      $sex=test_input($_POST["sex"]);

}

}

  ///格式转换工具

  function test_input($data)

{

      $data=htmlspecialchars($data);

      $data=trim($data);

      $data=stripcslashes($data);

      return $data;

}

  ?><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">

<fieldset>

<legend>个人资料</legend>

<ol>

<li>

名字:<input type="text" name="name" autofocus />

<?php echo $nameeor;?>            </li>

<br>

<li>

Email:<input type="text" name="email" autofocus />

<?php echo  $emaileor;?>            </li>

<br>

<li>

网址:<input type="text" name="weburl" />

<?php echo $weburleor;?>            </li>

<br>

<li>

性别:

<input type="radio" name="sex" value="男生" checked />男生

<input type="radio" name="sex" value="女生" checked />女生

</li>

<?php echo $sexeor;?>            <br>

<li>

备注:<input type="text" name="other" autofocus />

</li>

<?php echo $othereor;?>            <br>

</ol>

</fieldset>

<br>

<input type="submit" value="提交">

<input type="reset" value="重写">

</form>

  echo "<h2>您的信息内容是:</h2>";

  echo $name;

  echo "<br>";

  echo $eamil;

  echo "<br>";

  echo $weburl;

  echo "<br>";

  echo $sex;

  echo "<br>";

  echo $other;

  ?></body>

</html>

如果出现问题,最好先查看环境是否正确!

上一篇 下一篇

猜你喜欢

热点阅读