phpsql-injectionmysql-real-escape-stringmagic-quotes

PHP Magic Quotes Question


I've never programmed in an environment with magic quotes turned on before. Now I'm working on a project where it is. This is how I've been setting up user accepted data situations:

$first_name = $_POST['first_name']
if(!get_magic_quotes_gpc()) {
    $first_name = mysql_real_escape_string($first_name);
}

With that filtering, am I still open for SQL injection attacks when magic quotes is enabled?

I'm really only concerned about any kind of SQL injection that will break my queries... Other whitelisting, htmlspecialchar() -ing etc. is in place for other areas.

Looking at some similar SO questions it seems that it's being advised to instead check for magic quotes, run 'stripslashes' on the data if it IS turned on, and then always run the escape function. I'm a little apprehensive to do it this way though because all of the existing code in the site assumes it's on.

Thanks!


Solution

  • Working with a legacy system can be a real PITA - especially with something like PHP which let some pretty egregious insecure code be written in the bad old days.

    I think you've actually already answered part of your question:

    Looking at some similar SO questions it seems that it's being advised to instead check for magic quotes, run 'stripslashes' on the data if it IS turned on, and then always run the escape function. I'm a little apprehensive to do it this way though because all of the existing code in the site assumes it's on.

    I would also try and initiate a code review - find all places where use data is being written or used in database queries, and then replace with the more secure escaping. Eventually, you'll replace all of those squirrelly queries, and be able to turn magic quotes off for good.