3

Is there an easier way of safely extracting submitted variables other than the following?

if(isset($_REQUEST['kkld'])) $kkld=mysql_real_escape_string($_REQUEST['kkld']);
if(isset($_REQUEST['info'])) $info=mysql_real_escape_string($_REQUEST['info']);
if(isset($_REQUEST['freq'])) $freq=mysql_real_escape_string($_REQUEST['freq']);

(And: would you use isset() in this context?)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
ajo
  • 1,045
  • 4
  • 15
  • 30
  • 2
    Guys, I know you all want to get more reputation, but why no one explained that it is a weird idea at all?? And that only the necessary data should be sanitized, not all. – zerkms Nov 19 '10 at 07:55
  • @zerkms, Well I dont think this is a WEIRD IDEA, as it can come handy in certain situation. However I also agree that not all data should be sanitized except few who make up the query. – Starx Nov 19 '10 at 07:58
  • 2
    @Starx: you should not rely on any magic way to protect data from any kind of attacks. In each particular situation you should apply necessary function. IE: when (**and only when**) you need to perform an sql query - you apply `mysql_real_escape_string()` only to the variables used in the query. – zerkms Nov 19 '10 at 08:00
  • @zerkms, What are you exactly referring to When you said `Magic way`? – Starx Nov 19 '10 at 08:02
  • 2
    @Starx: the main idea of the topic is to get some magic code that makes variables safe to use in queries ;-) – zerkms Nov 19 '10 at 08:04

6 Answers6

31

To escape all variables in one go:

$escapedGet = array_map('mysql_real_escape_string', $_GET);

To extract all variables into the current namespace (i.e. $foo = $_GET['foo']):

extract($escapedGet);

Please do not do this last step though. There's no need to, just leave the values in an array. Extracting variables can lead to name clashes and overwriting of existing variables, which is not only a hassle and a source of bugs but also a security risk. Also, as @BoltClock says, stick to $_GET or $_POST. Also2, as @zerkms points out, there's no point in mysql_real_escaping variables that are not supposed to be used in a database query, it may even lead to further problems.


Note that really none of this is a particularly good idea at all, you're just reincarnating magic_quotes and global_vars, which were horrible PHP practices from ages past. Use prepared statements with bound parameters via mysqli or PDO and use values through $_GET or filter_input. See http://www.phptherightway.com.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    @ajo Data itself is never dangerous, it's the context you use it in that may make it dangerous. `mysql_real_escape` only protects you when using data in SQL queries. If you're not using the data in SQL queries it will (may) only change the data, it won't make it any more or less save. If you echo the data into an HTML page, `mysql_real_escaping` it won't help, you'd need to use `htmlentities` instead... Context is important! – deceze Nov 19 '10 at 09:31
  • Well, there was this comment of ajo I was responding to, before he deleted it... I'll leave my comment here anyway. – deceze Nov 19 '10 at 09:33
  • 1
    I know by now everyone should be using `PDO` or `prepared statements`, but wouldn't this fall over when a `$_REQUEST` or $_POST variable is an `array`? for example, when submitting multiple checkbox values with same name – wired00 Apr 11 '13 at 00:44
  • @wired00 Yes, sure. Such wholesale escaping actually never was a great idea to begin with, but in the limited case of the OP it served a purpose. It should only be applied if you know what you're doing though (as always). – deceze Apr 11 '13 at 00:54
  • cool thanks for the clarification. Yeah I assumed in the OP case its fine, because he is using a `$_GET` anyways. Just wanted to confirm for my own case. We have a TONNE of legacy code which is unviable to convert to `PDO`, so having to use `mysqli_real_escape_string()` – wired00 Apr 11 '13 at 01:01
  • @wired If you're using mysqli, use prepared statements! Or was that a typo? – deceze Apr 11 '13 at 01:04
  • not a typo we are using `mysqli_` but as I mentioned there is FAR too much legacy code to convert everything over. So we only have the option of using mysqli_real_escape_string() against variables. I know full well that we need either use prepared statements or PDO Anyway thats the matter of another discussion :) – wired00 Apr 11 '13 at 01:24
  • don't you think this magic_quotes reincarnation is not that good as it seemed to be four years ago? ;) – Your Common Sense Apr 24 '14 at 14:00
  • @You Oh, certainly. :) – deceze Apr 24 '14 at 14:05
  • The keys of a get or post parameters need to be escaped too if you gonna use them in your query! Let's not forget! – e-motiv Dec 20 '18 at 18:35
4

You can also use a recursive function like this to accomplish that

function sanitate($array) {
   foreach($array as $key=>$value) {
      if(is_array($value)) { sanitate($value); }
      else { $array[$key] = mysql_real_escape_string($value); }
   }
   return $array;
}
sanitate($_POST);
Ryan
  • 14,682
  • 32
  • 106
  • 179
Starx
  • 77,474
  • 47
  • 185
  • 261
1

To sanitize or validate any INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV, you can use

Filtering can be done with a callback, so you could supply mysql_real_escape_string.

This method does not allow filtering for $_REQUEST, because you should not work with $_REQUEST when the data is available in any of the other superglobals. It's potentially insecure.

The method also requires you to name the input keys, so it's not a generic batch filtering. If you want generic batch filtering, use array_map or array_walk or array_filter as shown elsewhere on this page.

Also, why are you using the old mysql extension instead of the mysqli (i for improved) extension. The mysqli extension will give you support for transactions, multiqueries and prepared statements (which eliminates the need for escaping) All features that can make your DB code much more reliable and secure.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
0

As far as I'm concerned Starx' and Ryan's answer from Nov 19 '10 is the best solution here as I just needed this, too.

When you have multiple input fields with one name (e.g. names[]), meaning they will be saved into an array within the $_POST-array, you have to use a recursive function, as mysql_real_escape_string does not work for arrays.

So this is the only solution to escape such a $_POST variable.

function sanitate($array) {
    foreach($array as $key=>$value) {
        if(is_array($value)) { sanitate($value); }
            else { $array[$key] = mysql_real_escape_string($value); }
   }
   return $array;
}
sanitate($_POST);
schier
  • 1
  • 2
0

If you use mysqli extension and you like to escape all GET variables:

$escaped_get = array_map(array($mysqli, 'real_escape_string'), $_GET);
vatavale
  • 1,470
  • 22
  • 31
-2

As an alternative, I can advise you to use PHP7 input filters, which provides a shortcut to sql escaping. I'd not recommend it per se, but it spares creating localized variables:

 $_REQUEST->sql['kkld']

Which can be used inline in SQL query strings, and give an extra warning should you forget it:

 mysql_query("SELECT x FROM y WHERE z = '{$_REQUEST->sql['kkld']}'");

It's syntactically questionable, but allows you escaping only those variables that really need it. Or to emulate what you asked for, use $_REQUEST->sql->always();

mario
  • 144,265
  • 20
  • 237
  • 291