duanming7833 2018-06-25 10:15
浏览 301
已采纳

如何保护HTML表单不受空白提交

Basically I'm using this tutorial: HTML FORM

Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php"" Is there a way to protect my form from blank submission when someone type the url and just press enter. Example: www.mywebsite.com/contact_mail.php

Thank you!

  • 写回答

5条回答 默认 最新

  • doudou3935 2018-06-25 10:27
    关注

    First you can use the required attribute on mandatory fields for client-side:

    <input type="text" name="mandatory_field" required>
    

    But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):

    if (empty($_POST['mandatory_field'])) {
        // print error message or redirect to form page
    }
    

    You can use isset() to verify if a field is submitted. Your validation could be:

    if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
        // print error message or redirect to form page
    }
    

    Other cases:
    If all fields are mandatory you could check with in_array():

    if (in_array(false, $_POST)) {
        // print error message or redirect to form page
    }
    

    If doing various data validation here is what I use to do with forms:

    $errors = [
        'empty field'           => empty($_POST['field']),
        'another error message' => $another_condition
    ];
    
    if (in_array(true, $errors)) {
        $error_message = array_search(true, $errors);
        // print or redirect, and you can tell the user what is wrong
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛