I have to write a base file for a larger program which will get functionality by include-files provided by other programmers. As I know neither the content nor the accuracy of the included code I have to ensure it will contain no target for MySQL injection. So in the beginning (right after setting the $server_conn) I ponder to add the following code:
$unsetvars = array_keys(get_defined_vars());
for ($i=0; $i<sizeOf($unsetvars); $i++)
{
if (substr($unsetvars[$i],0,1) != '_' && $unsetvars[$i] != 'server_conn')
{
unset($$unsetvars[$i]);
}
elseif ($unsetvars[$i] == '_GET' || $unsetvars[$i] == '_POST' || $unsetvars[$i] == '_REQUEST')
{
$subarray = array_keys(${$unsetvars[$i]});
for ($j=0; $j<count($subarray); $j++)
{
${$unsetvars[$i]}[$j] = get_magic_quotes_gpc() ? stripslashes(${$unsetvars[$i]}[$j]) : ${$unsetvars[$i]}[$j];
${$unsetvars[$i]}[$j] = mysqli_real_escape_string($server_conn,${$unsetvars[$i]}[$j]);
}
}
}
unset($unsetvars,$subarray,$i,$j);
But I still am insecure in several points:
1) Beside of $_GET, $_POST and $_REQUEST I have in mind to deal with $_FILES. Can you think of other Predefined Variables which might be an attack vector?
2) With the confinement of 1) will that reasonably avoid SQL injection from Website calls? (I know there might be still open attack vectors when programmers would be using external sources - but I don't think I will be able to control that)
3) Is there a way to inject variables to PHP beside of Predefined Variables? Otherwise the if-clause of the code above seems unnecessary?
4) Is this generally a useful approach and/or are there better ways to solve the problem? (I know in some cases the programmers won't get exactly the variables they expect, but that would be acceptable if SQL injection would be prevented)
In the end I have a meta question about the usage of stackoverflow: I found a related question "PHP SQL Injection Prevention [duplicate]" which in my opinion has not been answered properly (because the questioner stated "i have to submit the project in the next two days" - Considering my approach turns out to be usable for my problem it might also answer the related question: Would I post the approach as answer there too? Would I do so even though the related question is quite old (from 2011)?