webdad
webdad

Reputation: 11

secure php variable before insert it to database

Is this enough?

function cleanVar($str1){
 if(get_magic_quotes_gpc() == 0){
  $str1 = addslashes(htmlspecialchars($str1));
 }
 $str1 = stripslashes($str1);
 $str1 = htmlspecialchars($str1);
 $str1 = strip_tags($str1);
 $str1 = mysql_real_escape_string($str1);
 $str1 = str_replace("script","",$str1);
 $str1= str_replace("body","",$str1);
 $str1 = str_replace("select","",$str1);
 $str1= str_replace("insert","",$str1);
 $str1= str_replace("update","",$str1);
 $str1 = str_replace("on","",$str1);
 $str1= str_replace("<","&l",$str1);
 $str1 = str_replace(">","&",$str1);
 $str1 = trim($str1);
 return $str1;
}

Upvotes: 0

Views: 654

Answers (3)

OptimusCrime
OptimusCrime

Reputation: 14863

$str1 = str_replace("script","",$str1);
$str1= str_replace("body","",$str1);
$str1 = str_replace("select","",$str1);
$str1= str_replace("insert","",$str1);
$str1= str_replace("update","",$str1);
$str1 = str_replace("on","",$str1);

What will happen is you apply this function to a string containing: "This is a comment on the update on the situation in Iraq". You will strip away way too much information.

PDO is brilliant and you should consider switching from the outdated mysql-library to it.

Upvotes: 1

Rohan
Rohan

Reputation: 7976

Looking at the OWASP prevention sheets this pretty much covers is

 & --> &amp;
 < --> &lt;
 > --> &gt;
 " --> &quot;
 ' --> &#x27;     &apos; is not recommended
 / --> &#x2F;     forward slash is included as it helps end an HTML entity

https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

SQL injection is also included in this.

Also it's kind of weird to replace the actual SQL statements, it can become a problem if you are going to save actual words in your database.

Upvotes: -1

Troy McCabe
Troy McCabe

Reputation: 494

If at all possible, use PDO & prepared statements. It handles it all for you and ensures that you aren't losing any data (there's some weirdness with strip tags)

Upvotes: 3

Related Questions