Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

PHP clean string for mysql (See related posts)

// Function to clean up a string before using it in a mysql query

function clean_for_mysql($string,$max_length) {        
  $in_string = ltrim($string);       
  $in_string = rtrim($in_string);
  if (round($max_length) < 1) {  
    $max_length = 131072; // 128K
  }
  if (strlen($in_string) > $max_length) {
    $new_string = substr($in_string,0,$max_length);
  }
  $new_string = mysql_real_escape_string($new_string);
  return $new_string;
}

Comments on this post

CloCkWeRX posts on Feb 17, 2006 at 05:11
Why not rely on PEAR::DB to magically do it for you?

$result = $db->query("SELECT * FROM job WHERE job_id IN(?, ?, ?)", array("one", "two", "three")); 
Temp0001 posts on Feb 17, 2006 at 11:44
This function introduces a big security hole.

For example:
clean_for_mysql("Hack String'", 12);


Will return: Hack String\
(note the ending ' has been cut off)
Which when put in an SQL Query will escape the closing quote and allow injection.

MySQL will automatically cut your string to a certain length if you supply a limit for the field, so there is no need for the insecure substr().

Instead, just use:
mysql_real_escape_string(trim($string))
Charlie posts on Feb 17, 2006 at 20:04
PEAR DB, MySql and MySqli all define functions to escape strings that you are passing in as parameters and quote string that you are using for identifiers. (Table, View and Field names etc. etc)

Use them.
mvidberg posts on Feb 18, 2006 at 15:28
Security hole fixed... I moved the mysql_escape_string to be the last thing applied to the string.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts