To sanitize all user's input in PostgreSQL by PHP - php

This question is based on this thread.
Do you need the explicit sanitizing when you use pg_prepare?
I feel that pg_prepare sanitizes the user's input automatically such that we do not need this
$question_id = filter_input(INPUT_GET, 'questions', FILTER_SANITIZE_NUMBER_INT);
Context where I use Postgres
$result = pg_prepare($dbconn, "query9", "SELECT title, answer
FROM answers
WHERE questions_question_id = $1;");
$result = pg_execute($dbconn, "query9", array($_GET['question_id']));

According to the Postgres documentation on pg_prepare, all escaping is done for you. See the examples section where it lists the following code (including the comments):
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
Though it may be useful to note that they use single quotes (') instead of double quotes (") around the query string, as then $1 won't accidentally get interpolated into the string.

Related

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

Where can parameters be used in SQL statements?

I'm building a search engine, and I've been experimenting with structuring parameterized SQL statements in PHP. I was wondering what the rules are for where parameters can be used.
e.g. This works:
$var = $unsafevar;
$stmt = mysqli_prepare($connection, "SELECT * FROM users WHERE username = ?");
mysqli_stmt_bind_param($stmt, 's', $var);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
This doesn't:
$var = 'SELECT';
$var2 = 11;
$stmt = mysqli_prepare($connection, "? * FROM users WHERE username = ?");
mysqli_stmt_bind_param($stmt, 'ss', $var, $var2);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
Where can parameters be used and where can they not be?
Or, more simply, what does paramaterization literally do to the variables? Does it put single quotes around them? If that is the case, is there a way to paramaterize wildcards, column names, or the SQL clauses themselves?
Database, schema, table and column names cannot be parameterized - you would need to resort to dynamic SQL if you wish to "parameterize" them.
The linked article is an extensive discussion on the use of dynamic SQL, mostly dealing with SQL Server though applicable to most SQL databases.
My mnemonic for parameters is this:
Anywhere you could use a single scalar value, you can use a parameter.
That is, a quoted string literal, quoted date literal, or numeric literal.
Anything else (identifiers, SQL keywords, expressions, subqueries, a list of values for an IN() predicate, etc.) cannot be parameterized.

Should numbers from user input be quoted in MySQL queries to help avoid SQL injection attacks?

Should numbers from user input be quoted in MySQL queries to help avoid SQL injection attacks?
Say i have a form on a page asking for someone's age. They enter their age and hit submit. The following php code deals with the form submission: (age is an int field in the db table.)
$Number = mysqli_real_escape_string($dbc, $_POST["age"]);
$Query = "INSERT INTO details (age) VALUES ($Number)";
$Result = mysqli_query($dbc, $Query);
Instead of this, is there anything to be gained to enclosing the user input in single quotes, even though it is not a string? Like this:
...
$Query = "INSERT INTO details (age) VALUES ('$Number')"; <-- quotes
...
What about performing a SELECT? Is this:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = '$ID'";
$Result = mysqli_query($dbc, $Query);
better than:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = $ID"; <-- no quotes
$Result = mysqli_query($dbc, $Query);
NOTE: I am aware of prepared statements and usually use them over string concatenation but this is legacy code i'm dealing with. I want to secure it as best as i can.
If you add numbers, use the intval/floatval functions, don't use mysql_real_escape_string for those.
For everything you use mysql_real_escape_string for, you must use quotes, example:
$input = "foo'bar";
$input = mysql_real_escape_string($input);
//foo\'bar
mysql_query("SELECT $input");
//SELECT foo\'bar
//which is still an SQL syntax error.
You really shoud use sprintf, even if in legacy code it takes 2 mins to modify and is in my opinion totally worth the time.
Shamelessly ripped from php.net:
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
Your query is now pretty much safe from being passed the wrong types to it's fields and unescaped caracters.
You SHOULD use the PHP filters, and filter for numbers - even for ranges, regular expressions; with default values, NULL on failure, etc.
http://hu.php.net/manual/en/ref.filter.php
if the values come from a request variable, e.g. $_POST, see:
http://hu.php.net/manual/en/function.filter-input.php

Am I using mysql_real_escape_string right?

Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';

How to use prepared statements with Postgres

I know that I need prepared statements because I make more than one call to my database during one script.
I would like to get concrete examples about the following sentence
Look at typecasting, validating and sanitizing variables and using PDO with prepared statements.
I know what he mean by validating and sanitizing variables. However, I am not completely sure about prepared statements. How do we prepare statements? By filters, that is by sanitizing? Or by some PDO layer? What is the definition of the layer?
What do prepared statements mean in the statement? Please, use concrete examples.
What do prepared statements mean in
the statement?
From the documentation:
This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.
See pg_prepare
Example from the page linked above:
<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
?>
The MySQL documentation for Prepared Statements nicely answers the following questions:
Why use prepared statements?
When should you use prepared
statements?
It means it will help you prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Instead of placing a variable into the sql you use a named or question mark marker for which real values will be substituted when the statement is executed.
Definition of PDO from the PHP manual:
'The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.'
See the php manual on PDO and PDO::prepare.
An example of a prepared statement with named markers:
<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');
$sql = "SELECT username, password
FROM users
WHERE username = :username
AND password = :pass";
$sth = $pdo->prepare($sql);
$sth->execute(array(':username' => $_POST['username'], ':pass' => $_POST['password']));
$result = $sth->fetchAll();
An example of a prepared statement with question mark markers:
<?php
$pdo = new PDO('pgsql:dbname=example;user=me;password=pass;host=localhost;port=5432');
$sql = "SELECT username, password
FROM users
WHERE username = ?
AND password = ?";
$sth = $pdo->prepare($sql);
$sth->execute(array($_POST['username'], $_POST['password']));
$result = $sth->fetchAll();
How do we prepare statements:
You define a query one time, and can called it as often as you like with different values. (eg. in a loop)
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
$result = pg_execute($dbconn, "my_query", array("row two"));
$result = pg_execute($dbconn, "my_query", array("row three"));
see: http://us2.php.net/manual/en/function.pg-execute.php
Reply to Karim79's answer
This
$result = pg_prepare($dbconn, "query1", 'SELECT passhash_md5 FROM users WHERE email = $1');
seems to be the same as this
$result = pg_prepare($dbconn, "query1", 'SELECT passhash_md5 FROM users WHERE email = ?');
Conclusion: the use of pg_prepare and pg_execute makes PHP much more efficient, since you do not need to consider sanitizing. It also helps you in the use of PDO.

Categories