Anti-MySQL Injection function

Started on the old forum in January 2010 · view the original in the archive · old links redirect here

20 replies · 7,165 views · started 16 years ago · 1 min read

TL;DR · summary of 20 replies
  • The thread discusses various methods to prevent SQL injection, including functions provided and suggestions for implementation.
  • Users proposed different approaches such as using mysql_real_string_escape(), custom functions like anti_sql_injection(), or modifying .htaccess files.
  • Suggestions included using preg_replace instead of deprecated eregi_replace.
  • The thread concluded with a recommendation to place the anti-injection code in the core PHP for easy availability across all pages.

Written automatically from the replies by a language model on our own server. It can be wrong; the posts below are the source.

14 participants
riderz Lead · 975 posts #1

SQL Injection is security failure of the most hacked sites...

Here is Anti-MySQL Injection function:

function anti_injection($sql) {
   // removes words that contain sql syntax
   $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql);
   $sql = trim($sql); // strip whitespace
   $sql = strip_tags($sql); // strip HTML and PHP tags
   $sql = addslashes($sql); // quote string with slashes
   return $sql;
}

How to call the function:

<?php
$query = anti_injection($query);
?>

... or when you "post" the data:

<?php
$query = anti_injection($_POST['something']);
?>

or another one i found

if the topic was [HOW TO] Anti-SQL Injection Function I might have said that it did not depend on any given db, and there is a use for that, especially if you have SQL compliant functions for flat file, that said lets see what we can do to produce an anti-injection function the allows posting of (legal) SQL code in posts, and works irrelevant of SQL interface..

.. after a bit of research I have the following, which covers all eventualities

<?php

function anti_injection($sql,$debug=false) {
  if($sql=='') return;

  $single = false;   # do single quotes translation
  $double = false;   # do double quotes translation

//  $sql = trim($sql); # strip whitespace *(what if the first line is space indented? ie ascii art)
//  if (get_magic_quotes_gpc()) $sql = stripslashes($sql); # if you have problems with slashes
  $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters

  if(substr_count($sql,"'")==0) $single = false; else $single = true;
  if(substr_count($sql,'"')==0) $double = false; else $double = true;

  if($single) $sql = str_replace("'", '& #039;', $sql);  # for single quote characters
  if($double) $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters

  return $sql;
}

?>

the echo's are just for testing (eg: $safe_sql = anti_injection($data_to_be_sanitized,true);) , as these may be set differently on your PHP installation (not 110mb)

(NOTE: when copying either of these PHP quoted code functions, change "& #039;" to read "'" - minus space, its a quirk of the PHP code hiliter, it outputs "'" as "'")

that said, for pure speed I would use the following (less the comments)

<?php
function anti_injection($sql) {
  $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
  $sql = str_replace("'", '& #039;', $sql);  # for single quote characters (just in case)
  $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters (just in case)

  return $sql;
}
?>

or as antimatter might prefer

function sql_ai($sql){return str_replace('"','&quote;',str_replace("'", ''',htmlspecialchars($sql)));}

Jacques jacques@gw-designs.co.za http://coding.biz.tm Come join and lets make it a place to learn all the noobies how to code


NEVER FORGET TO CLICK THE TANX BUTTON IF U LIKE WHAT IM SHARING OR HELPING WITH

Anthony Developer · 82 posts #2

Thanks Nice Share

FREE International SMS

GYSMS.com Provides FREE International sms Reach over 775 networks in more than 221 countries at no cost to you. and the Good News is we own our SMS Hardware so there is no third party SMS API involved our services are completely Ad supported.....

http://gysms.com

Send FREE International MMS and Share Files worldwide using our MMS Service.

http://gysms.net

GTriddim Live Online Radio Station

http://www.gtriddim.com

wap-lord Junior · 31 posts #6

Does this protect you site for the injector.

ozziemale31 Lead · 861 posts #8

or a good way is how im doing my new script that means u have to re edit all the posts and gets

function cleanQuery($string) 
{
 $badWords = "(--)|(>)|(<)|(&)";
 $string = eregi_replace($badWords, "", $string);

 $string = mysql_real_escape_string($string); 

return $string;
 }

example:
for the gets

getbrip($sid);
$action = cleanQuery($_GET["action"]);
$sid = cleanQuery($_GET["sid"]);
$page = cleanQuery($_GET["page"]);
$who = cleanQuery($_GET["who"]);
$uid = getuid_sid($sid);

or for post

$staftxt = cleanQuery($_POST["staftxt"]);

External image (may be gone) External image (may be gone)

External image (may be gone)

*****

**Dont Ask Me Dumb Questions.Or you'l get a Dumb Answer.. Want A Profesional Logo or Theme For Your wap site Pm Me.If I Have The Time Ill Make It For Free ***

nclemale36 Lead · 537 posts #9

u can name the function anything u want ? am i right for example

[COLOR=#000000][COLOR=#007700]function [/COLOR][COLOR=#0000BB]cantinjecthere[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]) 
{
 [/COLOR][COLOR=#0000BB]$badWords [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#DD0000]"(--)|(>)|(<)|(&)"[/COLOR][COLOR=#007700];
 [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]eregi_replace[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$badWords[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]""[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]);

 [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]mysql_real_escape_string[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]); 

return [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700];
 }[/COLOR][/COLOR]

usage eg 
[COLOR=#000000][COLOR=#0000BB]$action [/COLOR][COLOR=#007700]= cantinjecthere[/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#DD0000][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#007700]([/COLOR][COLOR=#0000BB]$_GET[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"action"[/COLOR][COLOR=#007700]]);[/COLOR][/COLOR]

am i right ?

something else Fellow · 2,296 posts #10

yep but i would recommend using preg_replace instead of eregi_replace as its been deprecated since php 5.3.0

subzero Super moderator Fellow · 3,954 posts #12

Updated

//////////////////////// Anti Sql hit...
function check_injection() 
  { 
    $badchars = array("DROP","TRUNCATE", "SELECT", "UPDATE", "DELETE" , "UNION", "WHERE", "FROM","INSERT","ORDER BY","'","perm","',","validated","',perm='4',validated='1'#"); 
   
    foreach($_REQUEST  as $value) 
    { 
      if(in_array(strtoupper($value), $badchars)) 
      { 
      $logfile= 'logs/log.txt'; //chmod 777 
$IP = $_SERVER['REMOTE_ADDR']; 
$logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
$fp = fopen($logfile, "r+"); 
fwrite($fp, $logdetails, strlen($logdetails)); 
fclose($fp); 

       header('Location:antihack.fbi'); 

      } 
      else 
      { 
        $check = preg_split("//", $value, -1, PREG_SPLIT_OFFSET_CAPTURE); 
foreach($check as $char)
{
if(in_array(strtoupper($char), $badchars))
{
      $logfile= 'logs/log.txt'; 
$IP = $_SERVER['REMOTE_ADDR']; 
$logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
$fp = fopen($logfile, "r+"); 
fwrite($fp, $logdetails, strlen($logdetails)); 
fclose($fp); 

            header('Location:http://go-to-hell.com'); 
}}}} 
}

echo check_injection() or check_injection();

or this check_injection();

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

something else Fellow · 2,296 posts #14

try:

function unject($string){
return mysql_real_escape_string(preg_replace("/(--)|(>)|(<)|(&)/","",$string));
 }
Anshul Senior · 296 posts #15

here is one bt need some editing 😛

function minimum_version($vercheck) {
    $minver = (int)str_replace('.', '', $vercheck);
    $curver = (int)str_replace('.', '', phpversion());
    if($curver >= $minver)
        return true;
    return false;
}

function getvar($var) {
    global $HTTP_GET_VARS;
    global $HTTP_POST_VARS;
    $val = "";
    if (minimum_version('4.1.0')) { // when global variables changed
        if (in_array($var,array_keys($_GET))) {
            $val = $_GET[$var];
        } else if (in_array($var,array_keys($_POST))) {
            $val = $_POST[$var];
        }
    } else {
        if (in_array($var,array_keys($HTTP_GET_VARS))) {
            $val = $HTTP_GET_VARS[$var];
        } else if (in_array($var,array_keys($HTTP_POST_VARS))) {
            $val = $HTTP_POST_VARS[$var];
        }
    }

    remove_magic_quotes($val);
    return $val;
}

/*
 * This function removes slashes that may have been automatically
 * inserted by PHP if one of magic_quotes_* is On.
 *
 * Code by gordon at kanazawa dot ac dot jp as posted on php.net.
 * http://www.php.net/manual/en/function.get-magic-quotes-gpc.php
 */
function remove_magic_quotes(&$x) {
    if (is_array($x)) {
        while (list($key,$value) = each($x)) {
            if ($value) remove_magic_quotes($x[$key]);
        }
    }else if (ini_get('magic_quotes_sybase')) {
        $x = preg_replace("/''/", "'", $x);
    } else if (get_magic_quotes_runtime()) {
        $x = preg_replace("/\\\"/", '"', $x);
    } else if (get_magic_quotes_gpc()) {
        $x = stripslashes($x);
    }
}

$album_id = getvar("album_id");

BioBeo Developer · 67 posts #16

Man.. No Need to Update each and every single POST or GET method

All you can do this and Prevent Injecting via .htcaccess there you can add the queary string as :

union|select|insert|cast|set|declare|drop|update|md5|benchmark

No one could help you If you don't help yourself. My facebook

something else Fellow · 2,296 posts #17

BioBeo wrote: Man.. No Need to Update each and every single POST or GET method

All you can do this and Prevent Injecting via .htcaccess there you can add the queary string as :

union|select|insert|cast|set|declare|drop|update|md5|benchmark

if(isset($_REQUEST)){foreach($_REQUEST as $key=>$value){$_REQUEST[$key]=mysql_real_escape_string(htmlspecialchars($value));}}
marduck Junior · 12 posts #18

try it

function anti_sql_injection( $input ) { // daftarkan perintah-perintah SQL yang tidak boleh ada // dalam query dimana SQL Injection mungkin dilakukan $aforbidden = array ( "insert", "select", "update", "delete", "truncate", "replace", "drop", "or", ";", "#", "–", "=" );

// lakukan cek, input tidak mengandung perintah yang tidak boleh $breturn=true; foreach($aforbidden as $cforbidden) { if(strripos($input, $cforbidden)) { $breturn=false; break; } } return $breturn; }

LavalairLavalair.com

subzero Super moderator Fellow · 3,954 posts #19

i updated mine try that one and see if anyone can add there self owners lol

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

rayjee Developer · 99 posts #20

riderz wrote: SQL Injection is security failure of the most hacked sites...

Here is Anti-MySQL Injection function:

function anti_injection($sql) {
   // removes words that contain sql syntax
   $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql);
   $sql = trim($sql); // strip whitespace
   $sql = strip_tags($sql); // strip HTML and PHP tags
   $sql = addslashes($sql); // quote string with slashes
   return $sql;
}

How to call the function:

<?php
$query = anti_injection($query);
?>

... or when you "post" the data:

<?php
$query = anti_injection($_POST['something']);
?>

or another one i found

if the topic was [HOW TO] Anti-SQL Injection Function I might have said that it did not depend on any given db, and there is a use for that, especially if you have SQL compliant functions for flat file, that said lets see what we can do to produce an anti-injection function the allows posting of (legal) SQL code in posts, and works irrelevant of SQL interface..

.. after a bit of research I have the following, which covers all eventualities

<?php

function anti_injection($sql,$debug=false) {
  if($sql=='') return;

  $single = false;   # do single quotes translation
  $double = false;   # do double quotes translation

//  $sql = trim($sql); # strip whitespace *(what if the first line is space indented? ie ascii art)
//  if (get_magic_quotes_gpc()) $sql = stripslashes($sql); # if you have problems with slashes
  $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters

  if(substr_count($sql,"'")==0) $single = false; else $single = true;
  if(substr_count($sql,'"')==0) $double = false; else $double = true;

  if($single) $sql = str_replace("'", '& #039;', $sql);  # for single quote characters
  if($double) $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters

  return $sql;
}


?>

the echo's are just for testing (eg: $safe_sql = anti_injection($data_to_be_sanitized,true);) , as these may be set differently on your PHP installation (not 110mb)

(NOTE: when copying either of these PHP quoted code functions, change "& #039;" to read "'" - minus space, its a quirk of the PHP code hiliter, it outputs "'" as "'")

that said, for pure speed I would use the following (less the comments)

<?php
function anti_injection($sql) {
  $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
  $sql = str_replace("'", '& #039;', $sql);  # for single quote characters (just in case)
  $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters (just in case)

  return $sql;
}
?>

or as antimatter might prefer

function sql_ai($sql){return str_replace('"','&quote;',str_replace("'", ''',htmlspecialchars($sql)));}

wer i guna put dis code? In the core?

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close