如何在 PHP 中检查表单输入是否为数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/317916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:22:49  来源:igfitidea点击:

How can I check if form input is numeric in PHP?

phpvalidationnumeric

提问by markus

I need to be able to see if a form input in PHP is numeric. If it is not numeric, the website should redirect. I have tried is_numeric() but it does not seem to work.

我需要能够查看 PHP 中的表单输入是否为数字。如果它不是数字,则网站应重定向。我试过 is_numeric() 但它似乎不起作用。

Code examples will be nice.

代码示例会很好。

I am developing a shopping cart that accepts an integer value for the quantity. I am trying this:

我正在开发一个接受整数值的购物车。我正在尝试这个:

if(!is_numeric($quantity)){
                //redirect($data['referurl']."/badinput");
                echo "is not numeric";
        }

回答by markus

if(!is_numeric($quantity == 0)){
                //redirect($data['referurl']."/badinput");
                echo "is not numeric";

What you have here are two nested conditions. Let's say $quantity is 1.

您在这里拥有的是两个嵌套条件。假设 $quantity 为 1。

The first condition evaluates 1 == 0 and returns FALSE. The second condition checks if FALSE is numeric and returns FALSE because FALSE is not numeric.

第一个条件计算 1 == 0 并返回 FALSE。第二个条件检查 FALSE 是否为数字并返回 FALSE,因为 FALSE 不是数字。

just write:

写就好了:

if (!is_numeric($quantity))
{
    echo 'is not numeric';
}

回答by Rob

You should probably explain what you mean by "numeric" - integral, floating point, exponential notation etc? is_numeric()will accept all of these.

您可能应该解释“数字”的含义 - 积分、浮点数、指数表示法等?is_numeric()会接受所有这些。

If you want to check that a string contains nothing other than digits, then you could use a regular expression, e.g.

如果您想检查一个字符串是否只包含数字,那么您可以使用正则表达式,例如

/^\d+$/

If you're going to use the actual value as if it were an integer, you'll probably want to pass it through intval()anyway, which will return 0if the value cannot be parsed - if 0is a valid value, then you'll probably have to handle that in some way, maybe by constraining the lower range of the value.

如果您打算使用实际值,就好像它是一个整数一样,您可能intval()无论如何都希望通过它,0如果无法解析该值,它将返回- 如果0是一个有效值,那么您可能有以某种方式处理这个问题,可能是通过限制值的较低范围。

回答by infoxicated

It might also be wise to do some client side validation of the input using JavaScript.

使用 JavaScript 对输入进行一些客户端验证也可能是明智的。

The round-trip to the server and back is a long one for what might amount to a typo, and you'll reduce server overhead by making the client browser do a bit of the quality assurance beforehand.

往返服务器和返回的往返行程很长,可能会导致打字错误,您可以通过让客户端浏览器预先进行一些质量保证来减少服务器开销。

回答by gpojd

Check is_intand is_numeric. There are examples in each of the links. If you need more help, I would post the data you are having problems with and a code sample.

检查is_intis_numeric。每个链接中都有示例。如果您需要更多帮助,我会发布您遇到问题的数据和代码示例。

EDIT:

编辑:

$quantity == 0

will always be numeric, since it will return a boolean value (1 or 0). The correct thing to do it:

将始终是数字,因为它将返回一个布尔值(1 或 0)。正确的做法是:

if ( is_numeric( $quantity ) ) {
...
}

or

或者

if ( is_int( $quantity ) ) {
...
}

回答by John Conde

Another alternative is ctype_digit. From the docs:

另一种选择是ctype_digit。从文档:

Checks if all of the characters in the provided string, text, are numerical. Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

The above example will output:
The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

上面的例子将输出:
字符串 1820.20 不包含所有数字。
字符串 10002 由所有数字组成。
字符串 wsl!12 不包含所有数字。

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

回答by fausto

Try this:

尝试这个:

$numeric = "1"; //true default

$string = trim($_GET['string']);

$chkarray = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".");

for ($i=0; $i < strlen($string); $i++) { 
    if (!in_array(substr($string, $i, 1), $chkarray)) {
        $numeric = "0";
        break;
    }
}

回答by Tom Ritter

What Rob said, although instead of regular expressions to check for digits, I would use ctype_digit

Rob 所说的,虽然不是使用正则表达式来检查数字,但我会使用ctype_digit

回答by Mad Scientist

Use regular expressions: /^\d+$/should solve the problem

使用正则表达式:/^\d+$/应该可以解决问题

回答by Travis Leleu

tharkun has the best answer so far. If you're asking a question like this, it's my guess that you don't really want to start messing around with reg-exp's just yet.

到目前为止,tharkun 有最好的答案。如果你问这样的问题,我猜你还没有真正想开始弄乱reg-exp。

Re-think your logic. Why do you want to check to see if $quantity==0 is a numeric result? If you're trying to avoid errors b/c you think it's possible for quantity to not have an assigned value, you're checking a little late. This is a very common (and nefarious) security hole in your application -- if $quantity has a value derived at all from user input, please make sure to sanitize the input before it reaches this point in execution. As a smaller part of the issue, you will not need to assign a default value, because you sanitized your input previously (and that sanitization is where you'd deal with a 'no input' situation).

重新思考你的逻辑。为什么要检查 $quantity==0 是否为数字结果?如果您试图避免 b/c 错误,您认为数量可能没有指定值,那么您检查有点晚了。这是您的应用程序中一个非常常见(且邪恶)的安全漏洞——如果 $quantity 的值完全来自用户输入,请确保在输入到达此执行点之前对其进行清理。作为问题的一小部分,您不需要分配默认值,因为您之前已对输入进行了清理(并且清理是您处理“无输入”情况的地方)。

Good luck!

祝你好运!