Check $_POST['id'] is numeric then do this if not do otherwise

最后都变了- 提交于 2020-01-06 20:07:43

问题


Hello I seemed to be failing my code:

if (!empty($_POST['id'])) { 
    echo "empty";
} else {
    if (is_numeric($_POST['id'])) {
    echo "numeric!";
    } else {
    echo "not empty but not numeric how come?";
    }
}

My browser url: hxxp://localhost/upload/?id=9

OUTPUT: not numeric

how come?

please help.


回答1:


should use if(is_numeric($_GET['id'])) {


if (is_numeric($_GET['id'])) { 
    echo "yes numeric";
} else {
    echo "not numeric";
}



回答2:


first:

if (!empty($_POST['id'])) { 
    echo "empty";
} else ...

You are saying: If the variable is NOT empty, then echo "empty", and then you are checking if the empty variable is numeric or not (The code in the else is checking an empty variable, that's why it says it's not numeric)

Take out the Exclamation, and clarify yourself on using post or get method, as you are trying to get the POST variable when you passed it through GET




回答3:


See this question: $_POST Number and Character checker

// test.php

// testing with $_POST['id'] from forum with id = 5 and another test where id = new

$id = $_POST['editid'] ;
echo "<br>---".$id."---<br>";

if (empty($id)) { 
echo "<br>1: empty";
} else {
if (!is_numeric($id)) {
echo "<br>2: This is the number 5";
} else {
echo "<br>3: the must be the word new";
}
}

 // test 2 ... ctype_digit


if (empty($id)) { 
echo "<br>4: empty";
} else {
if (!ctype_digit($id)) {
echo "<br>5: This is the number 5";
} else {
echo "<br>6: the must be the word new";
}
}

// test 3 ... 



if (empty($id)) { 
echo "<br>7: empty";
} else {
if (!preg_match('#[^0-9]#',$id)) {
echo "<br>8: This is the number 5";
} else {
echo "<br>9: the must be the word new";
}
}

/**

result from 5


---5---

3: the must be the word new
6: the must be the word new
8: This is the number 5

results from "new"



**/



回答4:


I think you are passing parrameter via URL so use

if (is_numeric($_GET['id']))

Or use

if (is_numeric($_REQUEST['id'])) { 

Or else it will show an undefied variable hence will fallback to each block




回答5:


Its easy, "id" is in the $_GET array, but you check existance in the $_POST array

if (empty($_GET['id'])) { ... }

should be correct. And then you can use $_GET['id'] or $_REQUEST['id'].

Note: $_REQUEST holds all variables in $_POST and $_GET

The correct code should be:

 if (empty($_GET['id'])) { 
     echo "empty";
 } else {
     if (is_numeric($_GET['id'])) {
         echo "numeric!";
     } else {
         echo "not empty but not numeric how come?";
     }
 }

Instead of $_GET you can also use $_REQUEST



来源:https://stackoverflow.com/questions/13453778/check-postid-is-numeric-then-do-this-if-not-do-otherwise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!