is_real() is a function in PHP that was used in earlier versions to detect whether a variable was a floating point number. Functionally it is equivalent to is_float() or is_double() . For example:
$price = 12.99;
if (is_real($price)) {
echo "The price is a floating point number";
}
Although this code will work properly before PHP 7.4, running this code in modern PHP versions will generate a deprecation warning, and even remove this function completely in future versions.
During form processing, user-submitted data is usually received in the form of a string via $_POST or $_GET . Using is_float() or is_real() directly to determine these values usually returns false because the string is not a floating point type even if the content of the string is a number.
To solve this problem, we usually need to convert the string to a floating point number before performing type verification. Examples are as follows:
$input = $_POST['price'];
$floatVal = floatval($input);
if (is_float($floatVal)) {
echo "The input is a valid floating point number";
} else {
echo "Please enter the correct floating point format";
}
But there is a potential problem with this approach: floatval() will try to convert any string to a floating point number, which may return 0.0 even if the input is illegal. Therefore, a safer way is to use filter_var() with FILTER_VALIDATE_FLOAT for verification.
$input = $_POST['price'];
if (filter_var($input, FILTER_VALIDATE_FLOAT) !== false) {
echo "The input is a valid floating point number";
} else {
echo "Please enter the correct floating point format";
}
This method can effectively avoid the problem that mixed inputs such as "abc12.34" are mistaken for valid floating point numbers.
Suppose we have a form for submitting prices, with the submission address https://gitbox.net/submit.php :
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$price = $_POST['price'];
if (filter_var($price, FILTER_VALIDATE_FLOAT) !== false) {
echo "Price submission was successful,The value is:" . floatval($price);
// Here you can continue to write databases or other logic
} else {
echo "mistake:Please enter a legal floating point number!";
}
}
?>
<form method="POST" action="https://gitbox.net/submit.php">
<label for="price">Enter the price:</label>
<input type="text" name="price" id="price" required>
<input type="submit" value="submit">
</form>