Validate numeric value but exclude hex or sci notation - php

I used to rely on is_numeric() for making sure data passed from users is numeric. I recently discovered that users can also pass data 0xFF (hexdec = 255).
I'd like to disallow anything that is not a whole number (and not a hex representation).
Here's what I've tried so far.
$i_haxors_u = $_GET['id'];
$regex = '/[0-9]*/';
if (!empty($i_haxors_u) && !preg_match($regex, $i_haxors_u))
{
echo '<p>Invalid $i_haxors_u ' . strip_tags($i_haxors_u);
} else {
echo '<p>$i_haxors_u is numeric... maybe.';
}
This is still giving values like 0xFF a pass. How do I allow non-hex numbers only?
UPDATE Nov 12 2014.
Note that the selected answer works fine for data passed via GET, but will not work if a variable is set to a hex value.
$x = 0xFF;
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
$x = '0xFF';
if (is_numeric($x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
if (preg_match('/^[\d]+$/',$x))
{
echo "<p>$x is a number.";
} else {
echo "<p>$x is not a number.";
}
Prints
255 is a number.
255 is a number.
0xFF is a number.
0xFF is not a number.

use match non-digit in your regex: $regex = '/\D/';
assume failure and pass when confirming that no non-digits are present in the input.
following code succeeds on id =7, give fail on id = 7.2, 7.2x, ffff, 0xff, -1
$id = $_GET['id'];
//assuming failure:
$valid = false;
if (!preg_match('/\D/',$id)) { $valid = true; } //fail if containing non-digit
if ($valid) {
echo "$id provided is valid";
}
else {
echo "$id provided is not valid";
}

You need to use anchors and use + quantifier to only allow integers:
$regex = '/^\d+$/';
Using + quantifier will also let you take out !empty($i_haxors_u) condition since \d+ will enforce 1 or more digits.

It's just because you have to test all the number:
$regex = '/^[0-9]+$/';
no need to test empty with +

Related

Is there a simple way to use FILTER_SANITIZE_NUMBER_INT to validate a phone number (in a form)?

I am trying to validate a phone number using PHP, and would like to know if there's a way to do it with FILTER_SANITIZE_NUMBER_INT instead of regex.
I need the password to enforce the xxx-xxx-xxxx format (allows '-') and max length of 12 characters.
This is my code so far. Would this work to validate any number into the xxx-xxx-xxxx format?
$phone = clean_input($_POST["phone"]);
if (empty($phone)) {
$phoneErr = "Valid phone number required";
$isValid = false;
} else {
if (!filter_var($phone, FILTERSANITIZE_NUMBER_INT)) ;
$phone_to_check = str_replace("-", "", $filtered_phone_number);
if (strlen($phone_to_check) < 10 || strlen($phone_to_check) > 12) {
$isValid = false;
}
}
I would use preg_match instead as you can cover all your needs in one statement. This regex assures that the value must have 10 digits, with optional - after the third and sixth digits.
$phone = clean_input($_POST["phone"]);
$isValid = preg_match('/^\d{3}-?\d{3}-?\d{4}$/', $phone);
Demo on 3v4l.org
I prefer using preg_match() functions for this style of regex.
An example based on your pattern
$phone = '000-000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
For validating using FILTER_SANITIZE_NUMBER_INT() try code below
function validate_phone_number($phone)
{
$filtered_phone_number = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
if (strlen($filtered_phone_number) < 12) {
return false;
} else {
return true;
}
}
Now below is the usage of the function that we have just created:
$phone = "444-444-5555";
if (validate_phone_number($phone) == true) {
echo "Phone number is valid";
} else {
echo "Invalid phone number";
}

How to remove everything but allow letter, number and underscore?

How to remove everything but allow letter, number and underscore only in my validation for the username? I tried this code but it allows space:
function customUsername($username)
{
if (!preg_match('/^[a-z.,\-]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
Use the following regex
function customUsername($username)
{
if (!preg_match('/^[a-zA-Z0-9_]+$/i',$username))
{
$this->form_validation->set_message('customUsername', 'The username field');
}
}
You can use ASCII code of every letter, number and underscore.
follow this link for ASCII code http://ascii.cl/ .
jQuery is like this.
$('#keyId').keydown(function(e){
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
(key >= 23 && key <= 105)
);
});
So Simple It allow only Alphanumeric and Underscore only
<?php
$str='fdfdf5_';
if(preg_match('/^[a-zA-Z0-9_]+$/',$str))
{
echo "success";
}
else
{
echo "failed";
}
?>

$_POST Number and Character checker

This is a repeat question of Check $_POST['id'] is numeric then do this if not do otherwise
But..
The answers given do not answer the question IMHO.
The question is testing a $_POST string to see if it is a number or contains non-numeric characters. Not change the code to use $_GET.
The original question is as such:
if (!empty($_POST['id'])) {
echo "empty";
} else {
if (is_numeric($_POST['id'])) {
echo "numeric!";
} else {
echo "not empty but not numeric how come?";
}
}
I have tried, is_numeric() , but since $_POST delivers the variable as a string, even if it is a number this is useless.
I have tried, if(!preg_match('#[^0-9]#',$id)), but I have no idea why this doesn't work.
ctype_digit() I believe still has a problem with seeing all things from $_POST as strings, so no good.
There has to be a way, but I'm lost on how to do this. And no I can't use $_GET.
UPDATE ANSWER!!! (TYPO!!!!! god dammit!!!!):
// 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"
**/

How to compare 2 variable using php like this?

How to compare 2 variable using php like this ?
$aaa = "1234567890qwertyuiopsdflkjwerouioiuweewjkee";
$bbb = "1234567890qwertyuiop";
How to check
if(first char to twenty char of $aaa == $bbb)
{ echo "same"; }
else
{ echo "not same"; }
I assume you are searching for strncmp:
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.
if(strncmp($aaa, $bbb, 20) == 0) {
# First twenty characters match.
} else {
# First twenty characters don't match.
}
$aaafirst20 = $small = substr($aaa, 0, 20);
if(strcmp($aaafirst20 , $bbb){
}
else{
}
Try this :
You can use strcmp function for the same.
PHP docs # strcmp
if(strcmp($aaa,$bbb)){
echo "same";
} else {
echo "not same";
}
You can use strpos() to check if $bbb is found in $aaa, and starts at position 0.
if (strpos($aaa, $bbb) === 0) {
echo 'Same';
}
else echo 'Not same';
See demo
Your exact solution would be
// first reduce a to its first 20 characters
$trimmed = substr($aaa, 0, 20);
// now compare with b
if($trimmed == $bbb){
// same
}
Or, all in one line
if(substr($aaa, 0, 20) == $bbb){
// same
}

check if numeric php

my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}

Categories