1

I am trying to validate a form using php, the code i have doesn't prevent the form from being submitted when the inputs are invalid, however, the error messages that i would like them displayed do not show on the form, the form is returned empty of error messages even tho i have them echo'ed inside the form. could you help me display the error messages upon unsuccessful submission of the form ? i added my form code and the php code. both are seperate files , the action in the form leads to the php validation code like so (action = "report_form_php.php).

<form  method="post" onsubmit=" return formSubmit()" action="report_form_php.php">
      <div class="error1" id= "errorMsg">* Required Fields</div>
      <div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
      <div>
      <label for="staff_name"><b>Staff Name:</b></label> 
      <input  class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name"   > 
      </div><br>

      <div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
      <div>
      <label for="email"><b>Email:</b></label> 
      <input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff@wearview.com" >  
      </div><br>
      <div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
      <div>
      <label for="subject"><b>Subject:</b></label> 
      <input  class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title"  > 
      </div><br>

      <div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
      <div>
        <select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
            <option value="">Problem Type</option>
            <option value="Hardware">Hardware</option>
            <option value="Software">Software</option>
            <option value="Software&Hardware">Software & Hardware</option>
            <option value="Other">Other</option>
          </select>
      </div><br>
      <div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
      <div>
      <textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here"   rows="15" cols="90"></textarea>
      </div>          
      
      <div>
        <button class="field3" type="submit" class="btn">Submit</button>
        <input type="checkbox" id="notify" name="notify" value="">
        <label for="notify">Inform me by email when issue is resolved.</label> 
    </div>
</form>

<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";

// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["staffname"])) {
        $staffErr = "Staff Name is required";
    } else {
        $staff_name = test_input($_POST["staffname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
            $staffErr = "Only letters and white space allowed";
        }
    }

    // email validation:
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Please enter a valid email.";
        }
    }

    // subject validation:

    if (empty($_POST["subject"])) {
        $subjectErr = "Subject is required";
    } else {
        $subject = test_input($_POST["subject"]);
        // check if subject only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
        $subjectErr = "Only letters and white space allowed";
        }
    }

    // problem type validation:

    if (empty($_POST["problem_type"])) {
        $problemErr = "Problem type is required";
    } else {
        $problem_type = test_input($_POST["problem_type"]);
    }

    // description validation:

    if (empty($_POST["description"])) {
        $descriptionErr = "A Description is required";
    } else {
        $description = test_input($_POST["description"]);
    }
}


function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
    header("Location: insert_logs.php");
    exit(); 
} else {
    header("Location: log-it-reportsbeta.php");
    exit(); 
}
?>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Great Gobbs of white space do not help in understanding the code, however!!! Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Mar 04 '22 at 21:05
  • Did you set `ini_set('display_errors', 1);`? Because if you're not seeing any errors/notices for anything in PHP, your web server may be using a default of 0 (display nothing). – N. Kern Mar 04 '22 at 21:20
  • Where is `formSubmit()`, and what does it do? How does the browser get back to the form after `report_form_php.php`? – Don't Panic Mar 04 '22 at 22:23
  • @Don'tPanic the formSubmit() is a javascript function for client side validation , it is in a different js file, it works fine .. the issue is php , if the submission is successful, the brower goes to the page and i have there a return link , if the submission is not successful, the browser should reload the same page and displays error messages, the issue now is the lack of error messages – Blood Seeker Mar 04 '22 at 22:40
  • @N.Kern no, i didnt set that, i have another page where i didnt set that too, but it does display errors just fine .. – Blood Seeker Mar 04 '22 at 22:41
  • @RiggsFolly thank you for the tip, my skills are lacking when it comes to intentation, i will check the link :) now do you have any comment on the code itself, if you could locate the issue :) – Blood Seeker Mar 04 '22 at 22:43
  • AFAICT you want to set some PHP variables on one page (`report_form_php.php`) and display them on the next (`insert_logs.php`). HTTP is stateless, which means the variables you set up in the first request (when you submit the form) are completely lost and gone when you issue a new request/response (redirecting to another page). You can either put the code from `report_form_php.php` on the same page as your form, [and have the form POST to itself](https://stackoverflow.com/questions/17333901/php-form-on-submit-stay-on-same-page), so you can use the variables there ... – Don't Panic Mar 05 '22 at 23:51
  • ... or you need to look into one of the other ways of passing state between requests. There are many questions and examples here on SO about this, eg: https://stackoverflow.com/questions/871858/php-pass-variable-to-next-page – Don't Panic Mar 05 '22 at 23:51
  • Does this answer your question? [PHP Pass variable to next page](https://stackoverflow.com/questions/871858/php-pass-variable-to-next-page) – Don't Panic Mar 05 '22 at 23:51
  • @Don'tPanic I want to set error variables in (report_form_php.php) and display them on the page of the form itself which is (log-it-reportsbeta.php) , the (insert_logs,php) is the page where we go if the form was filled in correctly, if not, we stay on the same form page and errors should display. – Blood Seeker Mar 07 '22 at 09:14

1 Answers1

0

This basic php codes below should give you the ideas for 3 states of a form submission process to adjust your code properly.

  • success
  • system failure (bug or a temp. server issue for example)
  • invalid user data input
    // data were valid && script's aim is achieved
    if (isset($_SESSION['state']) && $_SESSION['state'] == 1) {
        // your thanks/result page's content here;
        echo 'Thanks. Transaction was successful.';
        unset($_SESSION['state']);
        return; // not to continue
    }
    
    // form not submitted yet
    if ( false === (isset($_POST['submit']) && $_POST['submit'] = "your val")) {
        require 'form.php';
        return; // not to continue
    }
    // form submitted
    require 'validate.php'; // PHP codes to validate data from POST global var.
    // data are valid
    if (valid($_POST)) {
        // try what you aim with valid data
        require 'perform_aim.php';
        if (perform_aim_successful()) { // for example: record was inserted
            $_SESSION['state'] = 1; // success state
            header("Location: YOUR URL", TRUE, 301); // prevents reprocessing by F5 ($_POST is empty again by 301.)
            exit; // exit after a redirect
        }
        else {
            echo 'Your data was OK but script was failed. Try again later';
        }
    }
    // invalid data
    else {
        print_r($err_msgs); // error messages from/by 'validate.php'
        require 'form.php';
    }
Ersin
  • 124
  • 3