views:

538

answers:

2

I am creating a website using PHP that makes use of a MySQL database and handles forms and variables from the URL. The variables are being using to dynamically construct SQL query strings. So i need a robust solution to make sure nobody is trying a SQL injection, etc.. A friend of mine has said that really i should only use stored procedures to access the database but that's not really feasible because the host i'm using doesn't allow these.

Here is the code i'm using (it's part of a class to wrap DB commands):

...
public function Sanitize($Variable)
{
    if(is_resource($this->ServerConnection))
    {
     $Variable = str_replace(";", "", $Variable);
     if(get_magic_quotes_gpc())
     {
      if(ini_get('magic_quotes_sybase'))
      {
       $Variable = str_replace("''", "'", $Variable);
      }
      else
      {
       $Variable = stripslashes($Variable);
      }
     }
     return mysql_real_escape_string($Variable, $this->ServerConnection);
    }
    else
    {
     $this->PrintError("The Sanitize function is not available as there is no server connection.");
    }
}
...

Is this function robust enough? Should i be doing anything else?

+2  A: 

Might be worth reading this post.

great_llama
A: 

What is the best way of ...

There is no best way. It depends on the context.

.. sanitising POST/GET variables from ..

It is a flawed mode of thinking that data are good or bad. Data is just data. It's the context in which it's used that makes it malicious or not. Some words may be bad if you execute them unadorned on a database server. Some words are bad if you display them to minors. It's about context.

troelskn