-2

My question is, how to using a script or other automatic method, change every

$_POST['*'] variables, in all PHP files, to

equivalents resistant to MySQL injection.

I found nothing at google at this topic.

This topic may be useful : How can I prevent SQL injection in PHP?

Thanks in advance!

Community
  • 1
  • 1
Marek Bardoński
  • 529
  • 1
  • 5
  • 14

2 Answers2

3

You cannot do this reliably. This is exactly what the PHP developers aimed to do with the ill-fated magic quotes feature, but it simply cannot work for everyone everywhere.

Security is not something you can bolt on an application after it's written; you have to design for it. In this case, it means that you need to revisit each and every SQL query and rewrite it in a secure manner.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

As Jon already said, each and every SQL query should be reviewed in your application.

However to answer your question with a possible (crappy) solution you could try this, given you are using Apache..

  1. setup apache and php.ini to allow setting auto_prepend_file via .htaccess files
  2. write php_value auto_prepend_file mysql_magic_quote.inc.php into you .htaccess
  3. put some code like this in mysql_magic_quote.inc.php

Example:

foreach($_POST as &$var)
    $var = addquotes($var);
foreach($_GET as &$var)
    $var = addquotes($var);
foreach($_COOKIE as &$var)
    $var = addquotes($var);
foreach($_REQUEST as &$var)
    $var = addquotes($var);

Please note:

  1. this basically simulates the deprecated setting magic_quotes_gpc, which has been deprecated for a reason!
  2. It is just a stupid example - it will definitely cause side effects!
  3. Don't do this, review your code instead!
  4. I did not use mysql_real_escape_string() here, because that would need an open database connection.
  5. I did not use mysql_escape_string() here, because that is deprecated as well.

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommended to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using doesn't have an escape function and the DBMS uses \ to escape special chars, you can use this function. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc was on by default before PHP 5.4, and it essentially ran addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Kaii
  • 20,122
  • 3
  • 38
  • 60