Jump to content

Best way to filtering to only integers?


dannyb785

Recommended Posts

Basically, the function I've been using to filter input to only integers is:

 

function make_int($input)
{
return (int)$input;
}

 

But I was wondering if it was better to use regex like preg_match... is my way sufficient or perhaps is one or the other harder on resources?

Link to comment
Share on other sites

<?php

$var = 1235523;

$var2 = -245;

$var3 = 'apple';

var_dump( isInt($var) ); // boolean true
var_dump( isInt($var2) ); // boolean true
var_dump( isInt($var3) ); // boolean false

function isInt( $var ) {
$var = (string)$var;
if( ctype_digit($var) || ($var[0] == '-' && ctype_digit(substr($var,1))) )
	return TRUE;
return FALSE;
}

?>

Link to comment
Share on other sites

No, regex would be a waste. But, that function is pretty much useless since you can just as easily use (int) $var instead of calling the function. You've basically created a function that does something that already exists.

 

I get what you're saying, but I only made it a function so that if I discovered that the function had a flaw in it that I could easily change it and not have to manually change every time I did that action on every page.

 

And about casting/filtering: I just need to make sure that the specific input is an integer and convert it to an integer if it's not. So if it was "9 lbs" that the result would be '9', and similar

Link to comment
Share on other sites

No, the manual tells you that. Floats are numeric, but they aren't integers.

 

So why not use is_int?

 

Because PHP is loosely-typed, and generally variables coming from outside sources will be a string.

 

It really depends how detailed you want your error reporting. Casting as an integer will close many potential attack vectors, but there's no way of knowing if the value being cast as an integer was actually an integer-equivalent prior to.

 

I think you're taking my post out of context though. I was responding directly to this

@xyph isn't is_numeric() doing the same thing?

 

I should've made that more clear.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.