is this a safe way to use SELECT via PDO [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to stop SQL Injection in PHP
How do I sanitize input with PDO?
I'm pulling in an id via $_GET. I just started using PDO and I'm unsure if this is safe or not. Obviously, the code below is using $_GET to grab an id. I'm not sanitizing it at all before I place it in the query. Is this safe?
<?php
if (isset($_GET['id'])) {
$blogid = $_GET['id'];
$post = $dbh->query("SELECT id, title, slug, body, image, author, date, category from blog WHERE id='$blogid' ORDER BY date DESC");
$row = $post->fetch(); ?>

I'm not sanitizing it at all before I place it in the query
Nope. Not safe at all. :)
You either need to escape it, or use a prepared statement. With PDO, I would use a prepared statement:
if (isset($_GET['id']) && is_string($_GET['id'])) {
$blogid = $_GET['id'];
$stmt = $dbh->prepare("SELECT id, title, slug, body, image, author, date, category from blog WHERE id= :id ORDER BY date DESC");
$stmt->execute(array('id' => $_GET['id']));
$row = $stmt->fetch();
}

It is NEVER safe to insert a variable in a SQL query without sanitizing/escaping it.
What you could do, if you don't want to escape it yourself is to use a prepare statement and bind your parameters.
You can check the PHP documentation...
About of how use PDO prepare:
http://php.net/manual/en/pdo.prepare.php
How to use the parameters binding:
http://www.php.net/manual/en/pdostatement.bindparam.php

Related

Escaping ORDER BY clause using mysqli_real_escape_string() function [duplicate]

This question already has answers here:
How do I set ORDER BY params using prepared PDO statement?
(7 answers)
Closed 5 years ago.
I am using different values in ORDER BY clause of SQL queries based upon user selection. How do I escape this selected value using mysqli_real_escape_string() function?
For example, the url is as following:
localhost/person/person_listing.php?sort_by=date_of_birth
Based on this I am using:
if (isset($_GET['sort_by'])) {
$sort_by = trim($_GET['sort_by']);
if (!empty($sort_by)) {
$order_by_sql = " ORDER BY $sort_by";
}
}
The question is, what is the best way to escape this type of add-on to SQL? Can the entire ORDER BY clause be escaped at once, or each value has to be escaped individually?
The best way to do this would be to use a prepared statement. Your code would look kind of as follows: (grabbed from here.
Basically, you add a question mark wherever you have a variable you would want to pass. And then you pass it with the mysqli_stmt_bind_param function. ss here means that you want to pass 2 strings.
if ($stmt = mysqli_prepare($link, "SELECT * FROM users WHERE Name=? ORDER BY ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $name, $sort_by);
}

How to insert a variable in count() function?

$id = $_GET['id'];
$result = mysql_query("select Count(id='$id') As Total from topics");
The above code is only working if we put count(id) but i want to get count of selected variable. How to insert id='$id' in count function it is not working please help related this.
You want a where clause in your sql query, which I believe would look like this:
select count(id) As Total from topics where id='$id'
note: depending on what type of column you have for your id field, you might need to drop the single quotes.
Warning
your code is vulnerable to sql injection you need to escape all get, post and request and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Your question isn't very clear but perhaps you're looking for COUNT CASE WHEN id = $id THEN 1 ELSE 0 END (you can even skip the ELSE 0 part I believe).
What actually are you trying to do is pretty unclear in the Question.
But if you are trying to count the number of rows then simple select count(*) as Total where {your condition} from table will will do for you.
$id get values of $_GET['id']
if you want other data, use $id="your data here"
The following should work:
$id = $_GET['id'];
$result = mysql_query("SELECT COUNT(`" . $id . "`) AS `Total` FROM `Topics`");
But do note that this isn't very secure since it will be vulnerable to SQL Injection attacks.
Count can be used as below
<?php
$shoes=array("nike","puma","lancer");
echo count($shoes);
?>
Read the documentation in the PHP manual on Count.For inserting id in count:
$result = mysql_query('SELECT COUNT(id) FROM clients');
$count = mysql_result($result,0);
echo $count;

MySQL Injection by LIKE operator [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I've below code in one of my php files to fetch data from DB:
$products = $this->db->get_rows('SELECT * from products WHERE shop_id='.$_SESSION['shop_id'].'AND tags,title,text LIKE \'%'.$_POST['search'].'%\'');
Is it problematic? I mean LIKE operator can be injected?
Edited
please provide examples of injecting in this way
Any operator can be injected without binding.
$_POST['search'] = "1%'; DROP TABLE myTable LIKE '%";
Would make
.... AND tags,title,text LIKE '%1%'; DROP TABLE myTable LIKE '%%'
Read on how to bind parameters.
Of course this can be injected, you need to sanitize your input. Right now you are taking raw post data and inserting it into your SQL statement.
You should run your POST data through some sort of data sanitization, something like mysql_real_escape_string or the like
Or at least prepared statements. let server side code do the work for you.
Never, ever, use database queries like that, don't construct a string with variables and use it for database activities.
Construct a string that will later on be prepared and executed, by inserting the variables into the string, making them not act like "commands" but as "values".
You can do it like this:
$query = "SELECT * from products WHERE shop_id = :shopId;"; // An example, you can finish the rest on your own.
Now, you can prepare the statement (I recommend using PDO for this).
$statement = $db->prepare($query); // Prepare the query.
Now you can execute variables into the prepared query:
$statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
If you're inserting or updating, then you would have wanted to do:
$success = $statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
which stores a boolean in $success, or you can fetch the values from a result if you're SELECTing:
$statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result )
{
// You can access $result['userId'] or other columns;
}
Note that you should actually make that be a function, and pass $shopId into the function, but not the session itself, and check if the session actually exists.
I recommend googling on how to use PDO, or take a look on one of my examples: How to write update query using some {$variable} with example
This is really bad. Pulling vars into an SQL statement without cleaning or checking them is a good way to get pwnd. There are several things that people can inject into code. Another injection method to watch out for, 1=1 always returns true.
$products = $this->db->get_rows('SELECT * from products WHERE shop_id='.$_SESSION['shop_id'].'AND tags,title,text LIKE \'%'.$_POST['search'].'%\'');
//This example expects no result from the table initially so we would blind attack the DB to pull the admin record.
$_POST['search'] = "-1\'; union all select * from users limit 1;";
Someone call pull up the top account in the database (like the admin).
$user_id = $this->db->get_rows('SELECT * from users WHERE email="'.$_POST['email'].'" and password="'.$_POST['password'].'"');
//This always returns true so now I'm the admin again
$_POST['password'] = "x\' or 1=1 limit 1";
You also want to be careful what you print on screen.
$user_id = $this->db->get_rows('SELECT * from users WHERE email="'.$_POST['email'].'" and password="'.$_POST['password'].'"');
A message that you echo that says "No user name exists for $_POST['email']" could be replaced with something else.
$_POST['email']=";
$fp = fopen('index.php', 'w');
fwrite($fp, \"header('Location: http://badwebsite.com;');\";
fclose($fp);";
index.php could now people to a different website entirely where an infected page exists or an infected page on the site.
If you're checking IDs do something like:
if(preg_match('!^[0-9]$!',$_POST['id'])){
$id = $_POST['id'];
} else {
//flush
}
or count for the number of possible records... if you're only expecting one and you get all of the records in the DB then it's an injection attempt.
if(is_numeric($_POST['id'])){
$id = $_POST['id'];
$count = mysql_result(mysql_query("select count(*) from users where id='$id''),0);
}

Is this kind of PDO query protected against SQL injection? [duplicate]

This question already has answers here:
How can prepared statements protect from SQL injection attacks?
(10 answers)
Closed 9 years ago.
First of all, yes, I've seen this Are PDO prepared statements sufficient to prevent SQL injection?, but it's not enough to answer my question, as I'm doing it differently.
Let's say I have code like this:
$userid = $_SESSION['data']['id'];
$query = "SELECT * FROM table WHERE userid='$userid'";
$action = $db->prepare($query);
$action->execute();
It's technically safe, as user can't affect to $userid, right? Say if I'm wrong on this.
But what if the code looks like this:
$userid = $_GET['id'];
$query = "SELECT * FROM table WHERE userid='$userid'";
$action = $db->prepare($query);
$action->execute();
Is it safe anymore? I'm unable to find any documentation about this that gives me black on white.
even if you have used PDO, your code is still vulnerable with SQL INjection because you have not parameterized the query, query must be parameterized in order for the values to be cleaned.
$userid = $_GET['id'];
$query = "SELECT * FROM table WHERE userid=?";
$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$action = $db->prepare($query);
$action->bindParam(1, $userid);
$action->execute();
The second statement isn't safe.
Instead, you should do something like
$stmt = $db->prepare('SELECT * FROM table WHERE userid=:id');
$stmt->bindParam(':id', $userid);
$stmt->execute();
Source
It's technically safe, as user can't affect to $userid, right? Say if I'm wrong on this.
You are wrong with that. Session data is outside data and must be treated with caution. This is because of:
SessionID and SessionName are given with the request directly. These values can be easily manipulated so that some different data is being put into the memory of your application.
Persistence. Session data can be modified in the persistence layer so it qualifies as input data always (!).
You are likely expecting an integer value, so make it one:
$userid = (int) $_SESSION['data']['id'];
Especially as you directly substitute the variable into your SQL query.
In the future don't think if it is safe. Consider to do things in a safe manner so that even if you missed something in another layer (like input through session) don't breaks the data-flow in your application.
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
...
$userid = (int) $_SESSION['data']['id'];
...
$query = "SELECT column FROM table WHERE userid = ?";
$stmt = $pdo->prepare($query);
$stmt->bindParam(1, $userid);
$stmt->execute();

Secure against SQL Injection - PDO, mysqli [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
I just found that my website is vunerable.
Since it's connected to a DB and have functions like: Register, Change Password, Notices, etc... and SUPOSING it's fully vulnerable.
What should I look for into the code in order to start making it safe?
I mean, I did some researches and everywhere, everyone says different things about security.
"Use PDO."
"Use mysql_real_escape_string."
"Use addslashes."
What exactly should I look for??
"$_POST" and "$_GET" variables??
"$_SESSION" variables?
SQL querys?
$sql = "select * from user";
$sql = "update user set user="new_user_name";
$sql = "insert into user (user) values ('userid')";
What should I do in each case?
Please, help me to know what and where I must go.
Thank you.
Following are the points to be considered for making safe php application.
USE PDO or mysqli
Never trust any inputs. Consider every variable viz $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER as if they were tainted. Use appropriate filtering measure for these variables.
To avoid XSS attack use php’s builtin functions htmlentities,
strip_tags, etc while inserting the user input data into the
database.
Disable Register Globals in PHP.INI
Disable “allow_url_fopen” in PHP.INI
Don’t allow user to input more data than required. Validate input to
allow max number of characters. Also validate each field for
relevant datatypes.
Disable error reporting after Development period. It might give
information about database that’ll be useful to hackers.
Use one time token while posting a form. If token exist and matches
the form post is valid otherwise invalid.
Use parametrized database queries
Use stored procedures
You can google for each point for more details.
HOpe this helps
What you should look for: Any data send from the client/user. Sanitize/escape this data.
PDO can sanitize queries (using PDO::prepare) and supports multiple SQL systems.
For MySQL, use MySQLi. mysqli_real_escape_string is the function to use for sanitizing data if you are using MySQL.
None of the SQL queries you provided are actually vulnerable to SQL injection.
SQL injection vulnerabilities happen because SQL input is not properly escaped.
For example:
$sql = "select * from users where user_id =" . $_GET['user_id'];
Consider if I passed in the following:
http://some_server.com/some_page.php?user_id=123%20or%201=1
The query when executed would end up being:
select * from users where user_id = 123 or 1=1
To fix this, use parameterized queries:
$query = "select * from users where user_id = ?"
When you bind the user_id value to the query, the data access layer will escape the input string properly and the following would be executed:
select * from users where user_id = '123 or 1=1' which would not return any rows, preventing the injection
If using PHP and the mysql extension:
$sql = "select * from users where user_id = '" . mysql_real_escape_string($_GET['user_id']) . "'";
Keep in mind you need to escape ALL input that is going into a SQL query:
$sql = "select id_column from some_table where id = 1";
$stmt = mysqli_query($conn, $sql);
if($stmt === false) die(mysqli_error($conn) . "\n");
while($row = mysqli_fetch_assoc($conn, $stmt) {
$sql = "update some_other_table set some_value = 'new value' where some_column = '" . mysqli_real_escape_string($conn, $row['id_column']) . "'";
....
}
This is because values you select from the database might include characters that are not safe for execution in a SQL statement, like the name "O'Hara" or example.
}
I've been using PDO.
An example for that in your case:
<?php
$stmt = $dbh->prepare("insert into user (user) values (?)");
$stmt->bindParam(1, $name);
$name = 'ValueHere';
$stmt->execute();
?>

Categories