zoukankan      html  css  js  c++  java
  • PHP——表单

    表单处理

    收集表单数据

    • $_GET
    • $_POST
      举个例子(以POST方式为例,GET和POST类似,直叙改方式为get,$_POST为$_GET)
    <html>
    <body>
    
        <form action="welcome.php" method="post">
            Name:<input type="text" name="name"><br>
            E-mail:<input type="text" name="email"><br>
            <input type="submit">
        </form>
    </body>
    </html>
    
    <html>
    <body>
    Welcome:<?php echo $_POST["name"];?><br/>
    Your email address is:<?php echo $_POST["email"];?>
    </body>
    </html>
    

    GET和POST的使用情况

    • GET可用于发送非敏感的数据(因为数据在URL上),且限制在2000个字符
    • POST可用于发送敏感数据(比如密码),且不限制字符数量

    表单验证

    目的

    对表单数据进行验证是为了防范何可和垃圾邮件
    http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

    步骤

    • trim() 去除用户输入数据中不必要的字符(多余的空格、制表符、换行)
    • stripaslashes() 删除用户输入数据中的反斜杠
    • htmlspecalchars() 将特殊字符转换为HTML实体
      举个例子
    <!DOCTYPE HTML> 
    <html>
    <head>
    <meta charset="utf-8">
    <title>表单验证</title>
    </head>
    
    <body>
    <?php
    $name=$email=$gender=$comment=$website="";
    
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
       $name = test_input($_POST["name"]);
       $email = test_input($_POST["email"]);
       $website = test_input($_POST["website"]);
       $comment = test_input($_POST["comment"]);
       $gender = test_input($_POST["gender"]);
    }
    
    function test_input($data)
    {
       $data = trim($data);
       $data = stripslashes($data);
       $data = htmlspecialchars($data);
       return $data;
    }
    ?>
    
    <h2>PHP表单验证实例</h2>
    <form method ="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
       名字:<input type="text" name="name"><br/>
       E-mail:<input type="text" name="email"><br/>
       网址:<input type="text" name="website"><br>
       备注:<textarea name="comment" rows="5" cols="40"></textarea><br/>
       性别:<input type="radio" name="gender" value="female">女
            <input type="radio" name="gender" value="male">男<br>
       <input type="submit" name="submit" value="Submit">
    </form>
    
    <?php
    echo "<h2>您输入的内容是:</h2>";
    echo $name;
    echo "<br/>";
    echo $email;
    echo "<br/>";
    echo $website;
    echo "<br/>";
    echo $comment;
    echo "<br/>";
    echo $gender;
    ?>
    
    </body>
    </html>
    

    表单必填

    目的

    • 防止必填类容未填

    方法

    • 用empty()对变量做判断,若是空则做出提示

    表单URL/E-mail

    验证名字

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


    验证E-mail

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


    表单完成

  • 相关阅读:
    Linux套接子(c语言)模拟http请求、应答
    709. 转换成小写字母
    1108. IP 地址无效化
    C++大作业——教职工管理系统
    贪吃蛇游戏 1.0
    getch()函数的使用方法及其返回值问题
    Open source project code
    slack Interface operation
    slack init: Simple interaction with slack bot
    mac 使用 Docker 搭建 ubuntu 环境
  • 原文地址:https://www.cnblogs.com/ceiling-/p/14338520.html
Copyright © 2011-2022 走看看