Jump to content
Sign in to follow this  
Guest Anonymous

[FAQ] Securing Input Variables

Recommended Posts

Guest Anonymous

Handling data in PHP applications is sometimes seen as a complex subject, but a little thinking can make life very simple:

Stage #1 is removing any slashes from the input variables $_GET, and $_POST.

 

<?php
function array_stripslashes( $value )
{
if (is_array($value))
	foreach ($value as $key => &$element)
		$element = array_stripslashes($element);
else if (is_string($value))
	$value = stripslashes($value);

return $value;
}

if (get_magic_quotes_gpc())
{
$_GET    = array_stripslashes($_GET);
$_POST   = array_stripslashes($_POST);
}
?>

 

Stage #2 is a simple set of functions to retrieve data from the two main arrays.

 

<?php
/**
**
**  <string> getStr( <string> $key, <string> $default = "" );
**
**/
function getStr( $key, $default = "" )
{
return isset($_GET[$key]) && is_string($_GET[$key]) ? trim($_GET[$key]) : $default;
}

/**
**
**  <integer> getInt( <string> $key, <integer> $default = 0 );
**
**/
function getInt( $key, $default = 0 )
{
return !is_null($tmp = getStr($key, null)) && preg_match("`^\d+$`ims", $tmp) ? @intval($tmp) : $default;
}

/**
**
**  <string> postStr( <string> $key, <string> $default = "" );
**
**/
function postStr( $key, $default = "" )
{
return isset($_POST[$key]) && is_string($_POST[$key]) ? trim($_POST[$key]) : $default;
}

/**
**
**  <integer> postInt( <string> $key, <integer> $default = 0 );
**
**/
function postInt( $key, $default = 0 )
{
return !is_null($tmp = postStr($key, null)) && preg_match("`^\d+$`ims", $tmp) ? @intval($tmp) : $default;
}
?>

 

Now, we are safe in the knowledge that all integers and strings coming from the two arrays are perfectly secure.

Two things of note here, if you are displaing any strings, you whould clean them through htmlentities():

 

<?php
echo htmlentities(postStr($username));
?>

 

and of course correctly escape your data if being sent to the database using mysql_real_escape_string():

 

<?php
$name = postStr("name");
$uid = 1; // the ID# of the user we are changing...
if (strlen($name))
{
$sql = sprintf("UPDATE `users` SET `username` = '%s' WHERE (`id` = %u)", mysql_real_escape_string($name), $uid);
mysql_query($sql);
}
?>

 

If you are wondering how to use it ... well just slap it into a common include file and you will always have these lightweight functions to hand.

References:

http://www.php.net/manual/en/function.htmlentities.php

http://www.php.net/manual/en/function.m ... string.php

http://www.php.net/manual/en/function.stripslashes.php

http://www.php.net/manual/en/function.g ... es-gpc.php

http://www.php.net/manual/en/function.isset.php

http://www.php.net/manual/en/function.is-string.php

http://www.php.net/manual/en/function.preg-match.php

http://www.php.net/manual/en/function.intval.php

http://www.php.net/manual/en/function.trim.php

http://www.php.net/manual/en/function.is-null.php

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

You make it sound SO easy!! :? lol

Is this used to secure your site against injections? :?

Share this post


Link to post
Share on other sites
Guest Anonymous

Re: [FAQ] Securing Input Variables

Not just SQL injection -- remember that is only one of several methods of attacking a site.

And it *is* easy, all you have to do is understand 10 functions... What on earth can be complex about that. Of course, I've spent a considerable number of years experimenting with each and every function in multiple combinations, and I still occasionally change my own (commercial) API routines, but essentially I've done all the work for you.

Most people screw themselves up with these - as they don't spend the time to actually read what I've posted, or read the relevant function definitions in the manual. Often people mix and match routines from several different people. This code as presented... works for me - perfectly, and I ran a *lot* of commercial sites with get attacked in some interesting methods. So, if it doesn't work for you -- re-read your documentation, re-read this topic, check your php.ini file(s), check your environment carefully, then go back to square #1 and experiment *until* you understand everything that is going on.

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

OK, I see. Thanks. I will certainly re-read, re-read again and re-read again!! I just can't get my head around security! :-P

Thanks Nyna, for taking the time to reply.

By the way, will this work, in a way:

$db->query mysql_escape("UPDATE users SET money=money-100 where userid=$userid", $c);

?

Share this post


Link to post
Share on other sites
Guest Anonymous

Re: [FAQ] Securing Input Variables

No - not in the slightest -- You've obviously not understands the basics...

mysql_real_escape_string is for escaping strings (odd that) not complete queries (otherwise it would be call mysql_real_escape_query), and contrary to what some people think, certain string data should never be escaped.

Learn the basics...

Correct usage (ignoring $link parameters for mysql_real_escape_string() and mysql_query())

 

$sql = sprintf("UPDATE `users` SET `username` = '%s' WHERE (`userid` = %u)", mysql_real_escape_string("Nyna"), 1);
mysql_query($sql);

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

I had a feeling it would be wrong.... :(

I just find it hard to learn off of websites (and sometimes books....I find it easier by being taught by others), but I will try my best.

Thanks, and sorry for being SO n00bish!

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

I see a bit of a dichotomy here. There's a whole range of functions that do a lot of things, and then there's The Ace that doesn't seem to understand why some or all of it is being used.

There's nothing wrong with that The Ace. The point though is that I see you trying to wrap your head around an entire sweet of functions when what you really need, is an understanding of each individual element.

To restate Nyna's original post in generic terms without any coding or functions being talked about, I'd say it like this:

Securing Input Variables amounts to "constraining" input from users to "parameters" that are exactly specified by you.

If that sentence doesn't make sense, then nothing about Nyna's post will make sense. I suspect that may be part of the problem here. You said Nyna made it seem so easy. Yes she does. And rightfully so because she understands the operation of every bit of that code and why it is in there.

 

function postStr( $key, $default = "" )
{
return isset($_POST[$key]) && is_string($_POST[$key]) ? trim($_POST[$key]) : $default;
}

 

Let's take just one small part of that code. postStr()

What's that do?

The first thing I'd say, is do you know what a TERNARY OPERATOR is? test condition ? true : false

It's like an if statement.

if (test condition) {

true

} else {

false

}

isset($_POST[$key]) && is_string($_POST[$key])

isset() <<<<<< is the variable set? $_POST[$key]

By definition, the $key is set because it's an argument in the function, but is $_POST[$KEY] in existence?

is_string() <<<<< is the variable a string?

if it's an array, an object, a boolean, or something other than a string, then no, it's not a string

So, check if the variable exists, and if it is a string.

We've "constrained" our "input" to a string at this point.

If the test is false, $defualt is used, which is ""

an empty string.

otherwise, we get a trim()

trim() <<<<<< removes empty spaces before, and after a string.

now we know that our string is just a string with no spaces before or after it.

 

now that we've done all that, we return our "string"

that one function does a heck of a lot. but without understanding every little bit of it, you wouldn't be securing a damn thing because how would you know if you used it right?

anyways, The Ace, take your time, and study, study, study.

Share this post


Link to post
Share on other sites
Guest Anonymous

Re: [FAQ] Securing Input Variables

You should be a teacher Floydian ... You've the patience of a saint :D

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

Thanks Floydian! I shall study, study, study! And I will be reading this topic A LOT!!

Thanks to the both of you. :)

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

I'd love to be a teacher. The problem is getting paid for it when you have no "paper" credentials... lol

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

 

You should be a teacher Floydian ... You've the patience of a saint :D

I must agree with that, you're one of the only 'advanced/good' coders that explain it so simply (no offence Nyna :P)...

Share this post


Link to post
Share on other sites
Guest Anonymous

Re: [FAQ] Securing Input Variables

None taken - I've been programming for so many years, I forget that I once knew bugger all - took me while to grasp the basics, but knuckling down, reading the manuals, experimenting with all sorts of data and functions gave me the abilities I have and I often expect a little too much from people with less experience.

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

Knowing how to do something, and knowing how to teach it are definitely two different skill sets.

It's been said that those that can't do something, teach it.

In other words, if you aren't good enough to make money doing something, perhaps you can make money teaching it instead. :)

Share this post


Link to post
Share on other sites

Re: [FAQ] Securing Input Variables

Wow, well written! I have read it, bookmarked it and will make it my number one priority to secure every one of my input variables!

It's nice to see posts on CE that are to the point and that provides resources as well. Posting the php manual references is extremely helpful for me. I will read every little detail this week and go through all my input variables.

Nice work Nyna and Floydian!

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Sign in to follow this  

×
×
  • Create New...