简体   繁体   中英

Validating form input for data type and range in PHP

My question is fairly simple. I need to verify the user enters 3 integer values, each between 0 and 100, or print an error message.

Right now the error messages work correctly, but when I enter 3 CORRECT numbers, I still get an error.

<?php
// get the data from the form
$grade1 = $_POST["grade1"];
$grade2 = $_POST["grade2"];
$grade3 = $_POST["grade3"];

// TEST FOR INTEGER
if (!is_int($grade1) || !is_int($grade2) || !is_int($grade3)) {
    $error_message = 'Please enter three numeric grades.'; 
}

// TEST FOR RANGE
if ($grade1 < 0 || $grade1 > 100 || $grade2 < 0 || $grade2 > 100 || $grade3 < 0 || $grade3 > 100) {
    $error_message = 'You must enter grades between 0 and 100.';
}

if ($error_message != '') {
    include('index.php');
    exit();
}

// calculate grade average
$average = ($grade1 + $grade2 + $grade3) / 3;
$average_f = number_format($average, 0);

// calculate letter grade
if ($average >= 90 && $average <= 100) {
    $letter = "A";
} else if ($average >= 80 && $average < 90) {
    $letter = "B";
} else if ($average >= 70 && $average < 80) {
    $letter = "C";
} else if ($average >= 60 && $average < 70) {
    $letter = "D";
} else if ($average >= 0 && $average < 60) {
    $letter = "F";
}

?>

I hope it's easy to tell what I'm trying to do and how I'm doing it. Thanks in advance for your suggestions :)

General suggestions and may be the error you get:

You are barely using the variables without checking whether they are set.

You need to use isset before checking variable and $_POST type.

Example:

if(isset($_POST['grade1']))
{
    $grade1=$_POST['grade1'];
}

So that if a user does not submit value for grade1 , you will not get Undefined index error .

Similarly for your error variable $error_message too. Because if there are no errors, say the user entered 3 integers between 0 & 100, you will get Undefined variable $error_message .

The issue comes from is_int() it checks if the variable is an integer however client input (POST, GET, headers, etc..) are always strings. That's why it's failing.

if (!is_numeric($grade1) && !is_numeric($grade2) && !is_numeric($grade3)) {
    $error_message = 'Please enter three numeric grades.'; 
}

Also, you where checking if any of these values where integers not all of them. So replace the || (or) with && (and).

Also, you compare $error_message with an empty string perhaps its more neat to either check if $error_message isset() or checking if its empty() as its easier to read through and even faster in execution as well. But overall its nothing to worry about cause either way it returns true if there's an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM