You can change a variable's type after it's been assigned a value. It's called typecasting. It forces the inputs to be numbers, and a check confirms that they are positive.
Function | Checks for |
---|---|
is_array() | Arrays |
is_bool() | Booleans (TRUE, FALSE) |
is_float() | Floating-point numbers |
is_int() | Integers |
is_null() | NULLS |
is_numeric() | Numeric values, even as a string |
is_resource() | Resources, like a database connection |
is_scalar() | Scalar(single-valued) variables |
is_string() | Strings |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>Validating Data by Type</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php if (isset($_POST['submit'])) { process_form(); } else { display_form();// display form for the first time } function display_form() { echo <<<HTML <h2>Validating Data by Type</h2> <form action = "$_SERVER[SCRIPT_NAME]" method="post"> Quantity: <input type="text" name="qty" size="5" maxlength="10" value="10" /> <br /> Price: <input type="text" name="price" size="5" maxlength="10" value="12.99" /> <br /> Tax (%): <input type="text" name="tax" size="5" maxlength="10" value="8.25" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> HTML; } function process_form() { //display to see what we got from the form for the comments // cast all the variables to a specific type $qty = (int) $_POST['qty']; $price = (float) $_POST['price']; $tax = (float) $_POST['tax']; // all variables should be positive if ( ($qty>0) && ($price>0) && ($tax>0) ) { // calculate the total $total = ($qty * $price) * (($tax/100)+1); // print the result echo "<p>quantity: $qty<br />price: $" . number_format($price, 2) . "<br />total: $" . number_format($total, 2) . "</p>"; } else{ // invalid data echo "<p>Please enter valid data</p>"; } echo "<p><a href=\"$_SERVER[SCRIPT_NAME]\">Try again?</a></p>"; } ?> </p> </body> </html> |