Jump to content

Validate is_numric


bob_the _builder

Recommended Posts

Hi,

I have a function:

[code=php:0]function ValidateNumric($value) {
$value = is_numeric($value);
return $value;
}[/code]

Being trying a impliment an easy way to validate any $_POST or $_GET id's using the above function and show an error message about altering the url.

Anyone got any nifty ways to check any id parsed, keeping code to a minimum using the above function?


Thanks
Link to comment
Share on other sites

Not really sure about what you're asking but how about this

[code]
function ValidateNumric($value) {

is_numeric($value)? return true: return false;

}
[/code]
Then just use like this (put at the top of the page for example):
[code]
if(isset($_GET['id']) ){
if(ValidateNumric($value) ){
                //do stuff
        }else{
              echo 'bad bad..';
        }
}
[/code]
Link to comment
Share on other sites

Hi,

I was thinking of some universal way where I could add a snippet at the top of my page which has a few insert, update, delete querys ..

Basically all in one check post and get id's, if not a numric then echo error message and halt the script. rather than checking each query individually having the same piece of code several times on the page etc

Also whats the advantage to adding:

)? return true: return false; to the function?


Thanks
Link to comment
Share on other sites

i think is numeric returns bool value....

[quote]
Basically all in one check post and get id's, if not a numric then echo error message and halt the script. rather than checking each query individually having the same piece of code several times on the page etc
[/quote]

function get_my_var($var) {
  if(isset($_REQUEST['var']) ) {
  //valid here
    if(is_numeric($_REQUEST['var'])) {
      return $_POST['var'];
  } else {
    echo "not numeric";
  }
  }

}


USE get_my_var('name') insted of $_GET or $_POST['var ....
Link to comment
Share on other sites

Hmm
You could use $_REQUEST instead of get or post, since it checks both, although then you wouldn't know where the id was coming from which might pose some security issues.

Well, i might do it like this (disposing of the ValidateNumric since it's only a wrapper for an existing php function)

[code]
if(isset($_POST)){
  if(!is_numeric($_POST['id]) ){
      echo 'bad..';
      exit(); }
}elseif(isset($_GET)){
  if(!is_numeric($_GET['id]) ){
      echo 'bad'; //or generic display function for errors
      exit(); }
}
[/code]

Basically if a post request was made, it will check the $_POST['id'] and likewise for get requests.

'Also whats the advantage to adding: ? return true: return false; to the function?'

That's simply the ternary operator, a shorter version of if. Basically it goes like this: condition ? (condition is met) : (condition is not met). Basically none, just a preference - it makes the code clearer for me. Of course, when i was doing this i realised that your function is the same as the is_numeric function, it either returns true or false like the native php function. So there seemed to be no need for it (with or without the ternary operator - it's the same).

Link to comment
Share on other sites

Hi,

I have:

[code=php:0]if(isset($_POST['news_id'])) {
if(!is_numeric($_POST['news_id'])) {
echo 'Please dont edit the url!';
return;
}
}

if(isset($_GET['news_id'])) {
if(!is_numeric($_GET['news_id'])) {
echo 'Please dont edit the url! GET';
return;
}
}[/code]



at the very top of my page .. seems to work, but I thought there might be a cleaner way to check both in a single query.

Basically the id is sent across the url, then grabed as a hidden field in a form then submited the a sql query .. is the above code enough to make sure it goes thru as a numeric only?


Thanks
Link to comment
Share on other sites

This will make sure the value of id alway will be only numbers, note that - is_numeric() - will allow for example +0123.45e6 as a valid numeric value (see manual)

[code]
<?php

$id = $_GET['id'];
settype($id, "integer");

mysql_query("select * from articles where id = $id");

echo '<a href="article.php?id=$id">link</a>';

?>
[/code]
Link to comment
Share on other sites

[quote]+0123.45e6[/quote]

Wouldnt the 'e' get filtered as not numeric within that string anyway?

All im really looking for is to stop any sql injection via the get or post of the numeric id.

Also using:

[code=php:0]if(isset($_POST['submit'])) {

if($_POST['edit'] == 'edit') {
$sql = mysql_query("UPDATE news SET description='".ValidateInput($_POST['description'])."', filter='".ValidateInput($_POST['filter'])."'
WHERE news_id = '".$_POST['news_id']."'");
if (!$sql) { echo 'Failed, please contact the web administrator'; }else{ echo 'Sucessfully edited'; }
return;
}else{
$sql = mysql_query("INSERT INTO news (description, filter, posted)
VALUES('".ValidateInput($_POST['description'])."', '".ValidateInput($_POST['filter'])."', now())");
if (!$sql) { echo 'Failed, please contact the web administrator'; }else{ echo 'Sucessfully added'; }
return;
}
}[/code]


is that pretty safe from being altered in general also making sure the the id is numeric and making sure edit is = to edit?


Thanks
Link to comment
Share on other sites

[quote]All im really looking for is to stop any sql injection via the get or post of the numeric id.[/quote]

I would not depend on is_numeric but set it as integer if its always supposed to be integer

[code]
function SafeNumber($number)
{
settype($number,"integer");
return $number;
}
[/code]

12345kafhakfha would return 12345
123kfchkzh45 would return 123
kasgk123 would however return nothing
Link to comment
Share on other sites

yes - but you can compare them if you like

[code]
<?php

function SafeNumber($number)
{
$original = $number;
settype($number,"integer");
if($original == $number)
{
return $number;
}
else
{
die("error");
}
}

?>
[/code]

But, i think its good practice to query if the actual row really exists before altering or deleting anything
Link to comment
Share on other sites

Not having much luck with the error message, if I use:

[code=php:0]if ($_GET['edit'] == 'edit') {
$sql = mysql_query("SELECT description FROM news WHERE news_id = ".SafeNumber($_GET['news_id'])."");
while ($row = mysql_fetch_array($sql)) {
$description = stripslashes($row['description']);
}
}[/code]


if news_id isnt a number it processes the request anyway with a blank text area as there was no match with a db record.

Thanks
Link to comment
Share on other sites

it boils down to HOW you design your scripts in the end, and HOW safe that becomes.

If you are concerned about injection by the url and that is you major goal here, the SafeNumber will work. but i assume a user clicks a link that moves on becoming a visible GET - you are concerned that the user will alter the GET and refreshing the page to alter/delete even more stuff. Am i right in your concern?

Along with the GET['id'] or whatever, attatch a one-time mysql inserted md5 code along in the link, query db to find the same md5 code to verify that the link is used only once (first time real link). Delete the md5 code on the result page and no one can gain any success in refreshing the page as the matching code aint found and proper errormsg appears.

If you purely need url-injection prevention (as you should anyhow), including this snippet on top of every page will help:
[code]
<?php

$url = $_SERVER['REQUEST_URI'];
$pieces = explode("?", $url);
$gets = $pieces[1];
$pattern = '/script|<|>|%3c|%3e|SELECT|UNION|UPDATE|exe|exec|INSERT|tmp/i';
if (preg_match($pattern, $gets))
{
// kill
print "illegal";
die();
}

?>
[/code]
Link to comment
Share on other sites

Ok, gettin a bit lot now. I am using:

[code=php:0]function ValidateInput($value) {
$value = mysql_real_escape_string(trim(strip_tags($value)));
return $value;
}[/code]


to clean user input, and I understand that you should check post and get data contains the correct data for the query it is to perform.

I thought ValidateInput will clean user data enough to insert into the db and looking for a basic function to check post and get data.

Basically some general user security


Thanks
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.