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

发布于 2024-07-09 13:19:40 字数 302 浏览 9 评论 0原文

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

代码示例会很好。

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

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

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.

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";
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

寒冷纷飞旳雪 2024-07-16 13:19:52

尝试这个:

$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;
    }
}

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;
    }
}
晨光如昨 2024-07-16 13:19:51

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

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

若相惜即相离 2024-07-16 13:19:49

迄今为止,塔昆有最好的答案。 如果你问这样的问题,我猜你还不想开始搞乱 reg-exp。

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

祝你好运!

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.

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).

Good luck!

葬﹪忆之殇 2024-07-16 13:19:48

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

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

拥抱没勇气 2024-07-16 13:19:47

另一种选择是 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";
    }
}
?>

上面的例子将输出:
字符串 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
?>

Another alternative is ctype_digit. From the docs:

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.

<?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
?>
染年凉城似染瑾 2024-07-16 13:19:46

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

编辑:

$quantity == 0

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

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

或者

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

Check is_int and 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.

EDIT:

$quantity == 0

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

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

or

if ( is_int( $quantity ) ) {
...
}
虚拟世界 2024-07-16 13:19:44

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

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

/^\d+$/

如果您要使用实际值,就好像它是整数一样,您可能希望将其传递给 < a href="http://www.php.net/manual/en/function.intval.php" rel="nofollow noreferrer">intval() 无论如何,这将返回0 如果无法解析该值 - 如果 0 是有效值,那么您可能必须以某种方式处理该问题,也许通过限制价值。

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

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 0 if the value cannot be parsed - if 0 is a valid value, then you'll probably have to handle that in some way, maybe by constraining the lower range of the value.

江南烟雨〆相思醉 2024-07-16 13:19:44

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

往返服务器的时间很长,可能会出现拼写错误,您可以通过让客户端浏览器预先进行一些质量保证来减少服务器开销。

It might also be wise to do some client side validation of the input using 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.

以歌曲疗慰 2024-07-16 13:19:43
if(!is_numeric($quantity == 0)){
                //redirect($data['referurl']."/badinput");
                echo "is not numeric";

这里有两个嵌套条件。
假设 $quantity 为 1。

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

写吧:

if (!is_numeric($quantity))
{
    echo 'is not numeric';
}
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.

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.

just write:

if (!is_numeric($quantity))
{
    echo 'is not numeric';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文