We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

engel on 11/28/07


Tagged

sql function injection prevent


Versions (?)


Who likes this?

23 people have marked this snippet as a favorite

heinz1959
vali29
candes
luman
brent-man
jackol
darkphotn
skywalker
bioascii
Steffen82
JimiJay
cristianciofu
maxav
wbowers
leandemon
Zidizei
romanos
jamarama
Arzakon
pixelhandler
jdstraughan
Abe
Leech


Prevent SQL Injection


Published in: PHP 


Pass a user-inputted variable to this function in order to prevent SQL injection. Example:

mysqlquery("INSERT INTO table VALUES('" . sqlsanitize($_POST["variable") . "')");

Instead of:

mysqlquery("INSERT INTO table VALUES('" . $POST["variable"] . "'");

  1. /*
  2. Function: sql_sanitize( $sCode )
  3. Description: "Sanitize" a string of SQL code to prevent SQL injection.
  4. Parameters: $sCode
  5. The SQL code which you wish to sanitize.
  6. Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
  7. Requirements: PHP version 4 or greater
  8. Notes:
  9. Author: engel <engel@engel.uk.to>
  10. */
  11. function sql_sanitize( $sCode ) {
  12. if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
  13. $sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
  14. } else { // If PHP version < 4.3.0
  15. $sCode = addslashes( $sCode ); // Precede sensitive characters with a backslash \
  16. }
  17. return $sCode; // Return the sanitized code
  18. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: ckester on May 15, 2008

Helpful code, though I would just place addslashes($text) on any input field. Then always have stripslashes($text) when you withdrawl that information, simple easy code since you'll have to do strip the slashes anyway

Posted By: DaveChild on September 11, 2008

addslashes() is no good for preventing SQL injection - it is vulnerable to character encoding trickery.

You need to login to post a comment.