Script 13.5 Validation using filter_var()

Output

Widget Cost Calculator

Source
<?php # Script 13.5 - calculator.php #2
// This version of the script uses the Filter extension instead of typecasting.

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	// Sanitize the variables:
	$quantity = (isset($_POST['quantity'])) ? filter_var($_POST['quantity'], FILTER_VALIDATE_INT, array('min_range' => 1)) : NULL;
	$price = (isset($_POST['price'])) ? filter_var($_POST['price'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) : NULL;
	$tax = (isset($_POST['tax'])) ? filter_var($_POST['tax'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) : 0;
	
	// All variables should be positive!
	if ( ($quantity > 0) && ($price > 0) && ($tax >= 0) ) {

		// Calculate the total:
		$total = $quantity * $price;
		if($tax>0){
			$total += $total * ($tax/100);
		}
		// Print the result:
		echo '<p>The total cost of purchasing ' . $quantity . ' widget';
		echo ($quantity>1)?'s':'';
		echo ' at $' . number_format ($price, 2) . ' each';
		echo ($tax>0)?' with tax':' without tax';
		echo ' is $' . number_format ($total, 2) . '.</p>';
				
	} else { // Invalid submitted values.
		echo '<p class="error">Please enter a valid quantity, price, and tax rate.</p>';
	}
	
}
?>
<h2>Widget Cost Calculator</h2>
<form action="<?php echo htmlentities( $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ); ?>" method="post">
	<p>
		<label for="q">Quantity:</label> 
		<input id="q" type="text" name="quantity" size="5" maxlength="10" value="<?php if (isset($quantity)) echo $quantity; ?>" />
	</p>
	<p>
		<label for="p">Price:</label>  
		<input id="p" type="text" name="price" size="5" maxlength="10" value="<?php if (isset($price)) echo $price; ?>" />
	</p>
	<p>
		<label for="t">Tax (%):</label>  
		<input id="t" type="text" name="tax" size="5" maxlength="10" value="<?php if (isset($tax)) echo $tax; ?>" />
	</p>
	<p>
		<input type="submit" name="submit" value="Calculate!" />
	</p>
</form>