-4

what is the best way to sanitize this STRING to prevent SQL Injection?

$order_by_str = 'dest ASC';

EDIT

$whitelist = array('start','target','exec');

    if ( in_array( $order_by, $whitelist ) ) {
  $order_by_str = $order_by;
} else {
  $order_by_str = 'start';
}

I used now this, it seems to work for me.

The Masta
  • 837
  • 3
  • 9
  • 17
  • possible duplicate of [What's the best method for sanitizing user input with PHP?](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php) – N.B. Sep 20 '13 at 14:10
  • possible duplicate of [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – tlenss Sep 20 '13 at 14:10
  • Are you even taking in user input? I'm curious why you're worrying about sanitizing a regular string... – JRizz Sep 20 '13 at 14:10

2 Answers2

1

Given answers don't answer the question.

Although there is no way for the general purpose "string sanitization", one may notice that the given string is a very special one.
And the only way to sanitize it is whitelisting.

A best way to sanitize this string would be to have both parts separated and then both checked against whitelist.

So, instead of having this string whole, I'd have it in 2 variables, $_GET['orderby'] and $_GET['dir'].
And so the code would be

$allowed = array("dest","foo","whatever");
$key     = array_search($_GET['orderby'], $allowed));
$orderby = $allowed[$key];

$dir     = $_GET['dir'] == 'DESC' ? 'DESC' : 'ASC'; 

$query   = "SELECT * FROM t ORDER BY $orderby $dir";
Yang
  • 8,580
  • 8
  • 33
  • 58
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-2
$order_by_str = mysql_real_escape_string('dest ASC');

Hope this is what you are looking for!!!

Saurabh Jain
  • 25
  • 1
  • 8