1

Is there any point to use ctype_digit() with a comparison operator in if statement like this

if ($_GET['x'] > 0 && ctype_digit($_GET['x'])) {
    echo 'It is a Number';
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Toleo
  • 764
  • 1
  • 5
  • 19
  • Why both? If the first sentence returns true it automatically means it's a number, isn't it? – PedroFaria99 Mar 09 '18 at 14:49
  • there's a much simpler way to do this; what's the context of this? edit: and what does this have to do with [`security`](https://stackoverflow.com/questions/tagged/security)? – Funk Forty Niner Mar 09 '18 at 14:50
  • @FunkFortyNiner I remember being attacked by `XSS` attack using different `unicode` like `x3346`, So I feared if that possible on `> 0` if `0` has a `Unicode` with letters and has been accepted. – Toleo Mar 09 '18 at 14:51
  • @PedroFaria99 No, it could be a string containing a float or scientific notation. – Alex Howansky Mar 09 '18 at 14:51
  • @Toleo have you gone through these yet? https://www.owasp.org/index.php/Cross-site_Scripting_(XSS) --- https://stackoverflow.com/questions/39466104/xss-javascript-exploit-check --- https://stackoverflow.com/questions/39521743/how-to-exploit-http-header-xss-vulnerability --- https://stackoverflow.com/questions/5414962/protection-against-xss-exploits ? – Funk Forty Niner Mar 09 '18 at 14:54
  • @FunkFortyNiner Yes, But didn't know from them the risk that ishegg mentioned. – Toleo Mar 09 '18 at 14:56

2 Answers2

1

Not really. From the manual (emphasis mine):

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

So if x is a "non numeric string", your first check will fail and short-circuit the conditions, making ctype_digit() redundant in this situation.

However, be careful with this conversion. 123abc for example will return true for your first check (since for the comparison, 123 is used), so depending on how strict this is, maybe do a thorough check instead.

$s = "123abc";
var_dump($s > 0); // true
ishegg
  • 9,685
  • 3
  • 16
  • 31
-2

Yeah, it's possible if you want to make sure the input is a decimal number, and greater than zero

jwg
  • 5,547
  • 3
  • 43
  • 57
Apetu Gideon
  • 136
  • 1
  • 5
  • TBH, this answer is more of a comment and lacks detail and it needs to be improved. It's considered as being VLQ (very low-quality). – Funk Forty Niner Mar 09 '18 at 14:58