1

i have a simple Script to send a SQL Query to a PHP Script, but I do not know how I can protect it from SQL Injection.

Do you have an idea ? Thanks!

C# Script

private void SQLConnect()
{
string urlAddress = "XXX";

Query for the PHP Script

string query = "INSERT INTO user (name) VALUES ('Test-Name')";

Send the Query via POST to the PHP Script

using (WebClient client = new WebClient())
{
    NameValueCollection postData = new NameValueCollection()
{
{ "newQuery", query },
};
string pagesource = Encoding.UTF8.GetString(client.UploadValues(urlAddress, postData));
}
}

PHP Script

$db_server = xxx;
$db_benutzer = 'xxx';
$db_passwort = 'xxx';
$db_name = 'xxx';

Connect to Database

$mysqli = new mysqli($db_server, $db_benutzer, $db_passwort, $db_name);

if ($mysqli->connect_errno) 
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
} 
else
{
echo "Connected...\n";
}

Receive and Execute the Query from C#

$newQuery = $_POST["newQuery"];;

if ($mysqli->query($newQuery) === TRUE) 
{
echo("Success...\n");
}

mysqli_close($mysqli);
Kaputtnix
  • 9
  • 1
  • 2
    Related : http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php –  Aug 05 '16 at 09:32
  • It depends is your query generated by sources that you don't trust? If its only about the variables that are generated by untrusted sources you can use the answer of Ronald. – Poorya Mohammadi Aug 05 '16 at 11:50

1 Answers1

0

You could split the variables. So in your post you have a query with placeholders: INSERT INTO user (name) VALUES @p1

using (WebClient client = new WebClient())
{
    NameValueCollection postData = new NameValueCollection()
    {
        { "newQuery", query },
        { "P1", username }
    };
}

Then you use PHP to safely replace the parameters: http://php.net/manual/en/security.database.sql-injection.php

Ronald Emergo
  • 31
  • 1
  • 8