Jump to content

Archived

This topic is now archived and is closed to further replies.

bob_the _builder

Validate is_numric

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

Share this post


Link to post
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]

Share this post


Link to post
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

Share this post


Link to post
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 ....

Share this post


Link to post
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).

Share this post


Link to post
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

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
if you are not planning on logging anything special, then you can just cut your code in half, using $_REQUEST['id'], as suggested above. It will check the post and get, as it is an array of both.    since your error messages look the same and there seems to be no logging code or anything, then just use request.

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
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]

Share this post


Link to post
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

Share this post


Link to post
Share on other sites
why didn't you just say so, all this time i was under the impression that the numbers was the problem...

Share this post


Link to post
Share on other sites
I did in the first post, I guess that I assumed id to always be a number.

Trying to figure what you need for general site security in the sence of cleaning user input and stoping sql injections.

Thanks

Share this post


Link to post
Share on other sites

×

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.