PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] How can I validate an unsigned number in PHP?

 May 17, 2022     php, validation     No comments   

Issue

I'm not sure how to handle this one, and I've tried what to me are the most obvious solutions, but so far none have proved entirely satisfactory. I must be overlooking something very simple.

I have a form with an input of type text:

<input type="text" name="album_id">

I want to validate the input so the users only enters unsigned integer...

$required = array(); // required or invalid input

$tmp = trim($_POST['album_id']);

if (!is_int((int)$tmp)) {
   $required['album'] = 'The album id must contain a positive numeric value only.';
}

So far I've use !is_numeric($tmp) but a user can enter 9.2 or '1e4' and it will validate... so that one doesn't work.

I've also tried !is_int((int)$tmp) but for some reason, that one doesn't work (maybe it should but i'm doing it wrong...). I tried ctype_digit with no success. I'm probably overlooking something but not sure what.

How can I validate an unsigned number in php? No floats, negative numbers, etc... only a simple unsigned number (1 to n).


Solution

If you want to check if some variable only contains digits (which seems to be what you want, here), you'll probably have to go with ctype_digit().


Not sure what you tried, but something like this should work :

$tmp = trim($_POST['album_id']);
if (ctype_digit($tmp)) {
    // $tmp only contains digits
}


Answered By - Pascal MARTIN
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing