How to protect HTML form from blank submission

前端 未结 5 1961
梦毁少年i
梦毁少年i 2021-01-15 15:59

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

5条回答
  •  失恋的感觉
    2021-01-15 16:42

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

    
    

    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
    }
    

提交回复
热议问题