My technical blog didn't get off to a good start as Wordpress wouldn't save my post that contained PHP, HTML and SQL code. I'll have to modify Wordpress sanitation methods or roll my own basic blogging platform but what is the correct and safe way to store technical text with this kind of content in a MySQL database?
I assume you're using php.
Best is to use PDO, see: http://www.php.net/manual/en/pdo.prepare.php
From that site
Example #1 Prepare an SQL statement with named parameters
<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
Example #2 Prepare an SQL statement with question mark parameters
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
Alternatively use escaping
Use mysql_real_escape_string() to escape values before inserting them into the query.
$val1 = mysql_real_escape_string($_POST['value1']);
$query = "SELECT a,b,c FROM table1 WHERE a = '$val1' ";
// the quotes are essential ^ ^
Outputting code as code
When outputting the content use:
echo "the output is: ".htmlentities($output);
Related
sub completecheckout {
$cryptedcard = md5_hex($cardnum . $salt);
$grabcart = qq~select pid from cart where uid='$cookievalue'~;
$dbh = DBI->connect($connectionInfo, $user, $passwd);
$sth = $dbh->prepare($grabcart);
$sth->execute();
while (#row = $sth->fetchrow_array()) {
$insert = qq~insert transaction (uid, pid, cctype, ccnum)
values ('$cookievalue', '$row[0]', '$cardtype',
'$cryptedcard')~;
$dbh = DBI->connect($connectionInfo, $user, $passwd);
$sth = $dbh->prepare($insert);
$sth->execute();
}
$select = qq~select * from registered where id in
(select uid from transaction
where uid='$cookievalue')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($select);
$sth->execute();
#userinfo = $sth->fetchrow_array();
print header;
print qq~<html><head><title>YAY</title></head><body><p>CHECK MYSQL<p><p>#row</p></body></html>~;
}
I am trying to parse through the table cart and insert all the items associated with the user into a transaction table when they click the final checkout button. The above code will only insert the last row into the transaction table.
Here is code that inserts more than once, but does not work because $product is empty every other time.
sub completecheckout {
$cryptedcard = md5_hex($cardnum . $salt);
$grabcart = qq~select pid from cart where uid='$cookievalue'~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($grabcart);
$sth->execute();
#cart = $sth->fetchrow_array();
foreach $product (#cart) {
$insert = qq~insert transaction (uid, pid, cctype, ccnum)
values ('$cookievalue', '$product', '$cardtype',
'$cryptedcard')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($insert);
$sth->execute();
}
$select = qq~select * from registered where id in
(select uid from transaction
where uid='$cookievalue')~;
$dbh = DBI->connect($connectionInfo,$user,$passwd);
$sth = $dbh->prepare($select);
$sth->execute();
#userinfo = $sth->fetchrow_array();
print header;
print qq~<html><head><title>YAY</title></head><body><p>CHECK MYSQL<p><p>#userinfo</p></body></html>~;
}
Can anyone explain why this happens? I have been using while loops with fetchrow_array throughout my script to create tables linked to databases.
Firstly, you need to get into the habit of formatting your code better. It really helps following logic flow if the formatting imitates the logic.
Secondly, please turn on use strict and get used to declaring variables as close to their point of use as possible.
Thirdly, don't use global variables. Your subroutine uses $cardnum, $salt, $cookievalue and several other variables which are (presumably) defined outside of the subroutine. They should all be passed into the subroutine as parameters.
I know from previous conversations that you have no interest in learning Perl, you're just trying to get through a course that your college insists on. So I should make it clear that all of the advice above has nothing to do with Perl. That is all good general advice for any programming language.
Now, the specific problems.
You're creating a new $dbh any time you want to run a database query. Why not just connect once and then reuse that variable. A single $dbh can support multiple queries executing at the same time.
As Matt has pointed out in the comments, you are overwriting $sth. As I said above, a $dbh can support multiple concurrent queries, but each query needs its own statement handle. So you might do something like:
my $dbh = DBI->connect(...);
my $select_sth = $dbh->prepare($select_sql);
$select_sth->execute;
while (my #row = $select_sth->fetchrow_array) {
my $insert_sth = $dbh->prepare($insert_sql);
$insert_sth->execute;
}
Notice how I've a) reused the same $dbh and b) declared the $insert_sth within the loop so it's only available for the shorted possible amount of time.
If you were interested in Perl, I'd also show you how to make your code more efficient by using bind points in your SQL and passing extra parameters to execute(). I'd also recommend moving raw HTML out of your program and using a templating engine. But I strongly suspect you wouldn't be interested.
I just converted some MySQL to mysqli, but realized I do not have access to the mysqlnd driver with my server setup. So, I need to now convert to PDO which I have available.
I am trying to convert the following to PDO, but there is no bind_result available in PDO from what I have read. I need to use a prepared statement for this as there is user input.
$stmt = $mysqli->prepare("SELECT user,pass FROM test_users WHERE user = ?");
// bind params
$stmt->bind_param('s', $_POST['username']);
// execute prepared statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($ruser, $rpass);
// fetch values
$stmt->fetch();
// close statement
$stmt->close();
Can anyone help out quick? Here is what I have, but not sure how to retrieve the resulting values into useable variables...
$stmt = $db->prepare("SELECT user,pass FROM test_users WHERE user = ?");
// bind params
$value = $_POST['username'];
// execute prepared statement
$stmt->execute($value);
// stmt now holds results, but how can I retrieve them into useable values?
// ?
// close statement
$stmt->closeCursor();
You need to make yourself familiar with arrays. They are no less "useable" than regular variables.
And sometimes arrays even more usable, especially in your case.
$stmt = $db->prepare("SELECT user, pass FROM test_users WHERE user = ?");
$stmt->execute([$_POST['username']]);
$row = $stmt->fetch();
Now $row contains the row returned by query. Now you can test if any data returned and then use it.
For the password check you can use it this way
if ($row && $row['pass'] === whatever_hash_used($_POST['password']]))
{
unset($row['pass']);
$_SESSION['user'] = $row;
// etc
}
You can return values from a PDO query with the PDOStatement::fetch method. There are various ways of fetching the data, such as into an array, into an object, and into a lazy-loading object. The simplest of these, and the most appropriate in your circumstance, is an array. In this case, you need to use the PDO::FETCH_ASSOC constant.
$results = $stmt->fetch(PDO::FETCH_ASSOC);
You can then access $results['user'] and $results['pass'].
A nice way of improving this would be to fetch $user and $pass variables rather than an array. This can be done with the list construct:
list($user, $pass) = $stmt->fetch(PDO::FETCH_NUM);
The other problem with your code (as Your Common Sense may or may not be pointing out in the comments: it's a little hard to tell) is that your code to bind the variables isn't quite right. PDOStatement::execute expects an array:
$stmt->execute(array($value));
$stmt->execute([$value]); // from PHP 5.4
In my opinion, the nicer way to do this is with named parameters:
$stmt = $db->prepare('SELECT user, pass FROM test_users WHERE user = :user');
$stmt->bindParam(':user', $_POST['username']);
$stmt->execute();
list($user, $pass) = $stmt->fetch(PDO::FETCH_NUM);
i have searched and added some prevention code but i need expert advice am i correct ?
I have made seperate file for SQL connect but i have confusion whether i should use include, require, include_onces or any other ?
mysql_connect("localhost", "userr", "pass") or die(mysql_error()) ;
mysql_select_db("databse") or die(mysql_error()) ;
Here i have added two things UTF8 and mysql_real_escape_string.
$bad='anyone123';
$var = mysql_real_escape_string($bad);
$q = mysql_query('SET user_id UTF8');
$q = mysql_query("SELECT * FROM fbusers WHERE user_id = '$var'");
$r = mysql_fetch_array($q);
Please give me advice if how can i prevent injec. to 100%
i don't want my website to be hacked :(
Thank you
You need to use prepared statements for any queries that require user input. This sends the query and the parameters seperately and acts as a layer of security to catch any malicious input.
In PDO:
$stmt = $pdo->prepare("SELECT * FROM fbusers WHERE user_id = :var");
$stmt->execute(array(':var'=>$var));
In mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM fbusers WHERE user_id = ?');
$stmt->bind_param('s', $var);
$stmt->execute();
Maybe this post would help.
mysql_real_escape_string is preventing the unsanitized fields with bad characters from being added to the database. I don't want to have to specify all the fields on each form (since that's both cumbersome to do for each field and doesn't accommodate special characters which people may include or typos), but at the moment this code prevents anything from being inserted if any threatening characters are present in the unsanitized fields but still advances to the next page.
I'm also using jQuery validate on this page, but haven't been able to use that to prevent SQL injection.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$user_name = clean($_POST['user_name']);
$password = clean($_POST['password']);
//Create INSERT query
$qry = "INSERT INTO customer_info(fname, lname, gender, zip, email, phone, terms, security_question, security_answer, participating_retailers, notify_new_items, notify_promotions, priority1, priority2, priority3, priority4, priority5, privacy, user_name, password)
VALUES('$_POST[fname]','$_POST[lname]','$_POST[gender]','$_POST[zip]','$_POST[email]','$_POST[phone]','$_POST[terms]','$_POST[security_question]','$_POST[security_answer]','$_POST[participating_retailers]','$_POST[notify_new_items]','$_POST[notify_promotions]','$_POST[priority1]','$_POST[priority2]','$_POST[priority3]','$_POST[priority4]','$_POST[priority5]','$_POST[privacy]','$user_name','$password')";
$result = #mysql_query($qry);
$qry="SELECT * FROM customer_info WHERE user_name='$user_name' AND password='$password'";
$result=mysql_query($qry);
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_USER_ID'] = $member['user_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['fname'];
$_SESSION['SESS_LAST_NAME'] = $member['lname'];
session_write_close();
header("location: flatter-form.html");
exit();
mysql_query has been deprecated. PDO or mysqli both provide security against SQL injections. In addition to both having escaping functionality, PDO has the ability to also quote the string. Using prepared and parameterized queries makes it almost impossible for an attacker to inject SQL.
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Sample from: Prepared statements
Take a look at PDO vs. MySQLi.
I'm using the following code. The code works, but I want to change it so that it uses bindparam
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stqid=array();
for ($i=0; $i<$array_count; $i++){
$stqid[$i][0]=$lastInsertValue;
$stqid[$i][1]=$qid[$i][0];
$stqid[$i][2]=$qid[$i][1];
}
$values = array();
foreach ($stqid as $rowValues) {
foreach ($rowValues as $key => $rowValue) {
$rowValues[$key] = $rowValues[$key];
}
$values[] = "(" . implode(', ', $rowValues) . ")";
}
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
I replaced the following
$count = $dbh->exec("INSERT INTO qresults(instance, qid, result) VALUES ".implode (', ', $values));
with
$sql = "INSERT INTO qresults (instance, qid, result) VALUES (:an_array)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':an_array', implode(',', $values),PDO::PARAM_STR);
$stmt->execute();
but the insert doesn't work anymore (I didn't get any error messages though).
QUESTION: What am I doing wrong? How can I rewrite the code to use bindParam?
You're trying to create a statement and bind a param.
Statement are great because it potentially nullify any kind of SQL injection. And it does it by removing the concept of a query being only seen as a string. The SQL query is seen as a string with a parameter list and an the associated data as binded variables.
So the query is not only text, but text + data.
I mean:
This simple query:
SELECT * FROM A WHERE val="$param"
It is not safe because the query is only viewed as a string. And if $param is not checked, it is a SQLi hole.
But when create a statement, your query becomes:
SELECT * FROM A WHERE val=:param
Then you use bindparam to specify the value a :param. Which mean the value is not appended to the query string, but the query is already parsed and the data is provided.
In your case, you bind to the param :array an imploded array (I assume "data1", "data2", etc..). Which is only one parameter with the value as a string ( "data1, data2, data3..." ), so it will only result in one insert and not multiple insertions.
You can change your statement generation by generating a query with enough parameters to handle your array
$sql = "INSERT INTO qresults (instance, qid, result) VALUES ( :val0, :val1, :val2, ...)";
Then loop on your array and call the bindparam method for each parameters.
$count = 0;
foreach($values as $val)
{
$stmt->bindParam(":val$count", $val,PDO::PARAM_STR);
$count++;
}
This will work.
Edit: This solution show how it works for a one dimensional array, but can be easily extended to your problem by tweaking the statement query generation and modify the bindparam loop.
Your statement should looks like:
$sql = "INSERT INTO qresults (instance, qid, result) VALUES (:val0, :val1, :val2) , (:val3, :val4, :val5), ...";
You just have to count the number of element in your base array.