SQL-Injection prevention with if/else [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I just thought about the safety of my php script and read a lot about sql injections.Now I have a question to save me from it.Is it right when my script doesnt accept characters like ' , ; or " ? Or I just catch this from my Android app ? So I just see the problem in these caracters. Am I right ? Or is there sth I dont see ? If not what would be the easiest way to safe it ?

never check the string for injection, all you need to do is not concatenate the variable.
Use Prepared Statements.
a "example" in mysqli extract from http://www.wikihow.com/Prevent-SQL-Injection-in-PHP
$name = $_GET['username'];
if ($stmt = $mysqli->prepare("SELECT password FROM tbl_users WHERE name=?")) {
// Bind a variable to the parameter as a string.
$stmt->bind_param("s", $name);
// Execute the statement.
$stmt->execute();
// Get the variables from the query.
$stmt->bind_result($pass);
// Fetch the data.
$stmt->fetch();
// Display the data.
printf("Password for user %s is %s\n", $name, $pass);
// Close the prepared statement.
$stmt->close();
}
read: http://www.veracode.com/security/sql-injection
if your idea is check the variables for ' or " or ;, it's a hard endless job and in the end can solve by using PDO statment.

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);
}

mysqli insert error incorrect syntax [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I know a lot of people have the same error occasionally however I have looked at all previous answers and my code and i have tried col with and without backticks
Here is my current code
I also have tried with $var as well as just $var but same
if(!empty($_POST['email'])){
$date = date('dmY'); #Todays Date
$ip = str_replace('.','',$_SERVER['REMOTE_ADDR']); #Visitor IP
$verify = md5($date.$ip); #MD5 ENCRYPT THE 2 VALUES
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$link = mysqli_connect($dbh,$dbu, $dbp, $dbn);
$query = mysqli_query($link, "INSERT INTO `users` (`email`,`fname`,`lname`,`verify`,`password`,`joined`)
VALUES($email,$fname,$lname,$verify,$password,$date)");
if($query){
echo "inserted";
}
else {
echo mysqli_error($link);
}
There are other columns in the table however its only the above columns I want to add data for the rest can use default values initially
I've been looking at this code for so long now I just cant spot my problem, I know its something silly
The most mistake-proof way to add a variable into an SQL query is to add it through a prepared statement.
So, for every query you run, if at least one variable is going to be used, you have to substitute it with a placeholder, then prepare your query, and then execute it, passing variables separately.
First of all, you have to alter your query, adding placeholders in place of variables. Your query will become:
$sql = "INSERT INTO users (fname, lname) VALUES (?, ?)";
Then, you will have to prepare it, bind variables, and execute:
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $fname, $lname);
mysqli_stmt_execute($stmt);
As you can see, it's just three simple commands:
prepare() where you send a query with placeholders
bind_param where you send a string with types ("s" is for string and you can use it for any type actually) and than actual variables.
and execute()
This way, you can always be sure that not a single SQL syntax error can be caused by the data you added to the query! As a bonus, this code is bullet-proof against SQL injection too!
It is very important to understand that simply adding quotes around a variable is not enough and will eventually lead to innumerable problems, from syntax errors to SQL injections. On the other hand, due to the very nature of prepared statements, it's a bullet-proof solution that makes it impossible to introduce any problem through a data variable.

PHP insert ' into SQL [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
$type_of_poker = "hold'em no limit";
$sql = "INSERT INTO hands (type_of_poker) VALUES ('$type_of_poker')";
Im trying to put hold'em no limit into a SQL database but it won't let me
use ' i cant upload holdem no limit for a long list resones that have to do
with the rest of my code.
Instead of trying to escape the apostrophe, it is much better practice to use prepared statements and binded parameters which will also solve your problem. It solves your problem because you then don't need to escape the apostrophe ('):
$type_of_poker = "hold'em no limit";
//binding the parameters to your sql statement
$sql = "INSERT INTO hands (type_of_poker) VALUES (:type_of_poker)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':type_of_poker',$type_of_poker);
$stmt->execute();
Let me know if that worked for you! :)

Prevent SQL Injection by input type text [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I need some help and very very fast because my database was injected. I need at least a script that won't allow users to use :[Spaces, Sybols like ('*','=','/','.') and a list of words ('SELECT','FROM','WHERE')] in the text fields of my register form.
I heared something about mysql_real_escape_string(). What is this command doing? And don't post links to PHP: mysql_real_escape_string() Manual because I already read that.
There'a a right and a wrong way to approach this. The (usually) wrong way is to try and set up an input sanitation method (like a script) and hope that nothing gets through. It usually doesn't work.
What I recommend you to do is rewrite your PHP SQL queries to use MySQLi prepared statements. These are queries that are first converted from the common SQL syntax ("SELECT... WHERE...") to a statement your engine can work with, and only then are the fields replaced with your input, thus preventing SQL injection.
For example, the (very) susceptible SQL syntax:
"SELECT * FROM users_passwords WHERE user='" + user + "' AND pass='" + password + "'"
Can be converted to the following prepared statement:
"SELECT * FROM users_passwords WHERE user=? AND password=?"
And then, using the command bind_param(), you can safely replace the ? placeholders with your parameters after the statement is prepared. While the original SQL query allows you to use some basic injection techniques (like writing ' OR true OR '), prepared statements will not allow this.
Here's a working example:
// Create a new MySQLi connection object
$db = new mysqli('localhost','db_username','db_password','db_name');
// Create a new prepared statement
$stmt = $db->prepare('SELECT * FROM users_passwords WHERE user=? AND pass=?');
// Bind the parameters, in order, to the statement (s stands for string)
$stmt->bind_param('ss', username, password);
// Self-explanatory
$stmt->execute();
If you are in PHP then why don't you do it in your PHP script. sanitize all your user provided input in GET and POST and then move it forward to DB calls. That is the right way to do it.
I would strongly avoid constructing SQL query strings from any input even if you sanitize it.
The good way for security purposes and performance is to use functions to set the parameters:
for example:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
see http://php.net/manual/en/pdo.prepared-statements.php

Is this code using PDO secure? [duplicate]

This question already has answers here:
Are PDO prepared statements sufficient to prevent SQL injection?
(7 answers)
Closed 9 years ago.
I am new to PDO. As I heard PDO can prevent SQL injection attack.
Here's what I have written:
$db = new PDO('mysql:host=192.168.57.36; dbname=somedb; charset=UTF8', 'user1', 'pass1');
$sql = "SELECT * FROM table1 WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($tid));
Is it a secure code ? I guess prepared should do some securing acts but the variable is passed to query after it.
Shoud I use addParam before execution method?
Thank you.
Shoud I use addParam before execution method?
No.
Passing a variable into execute does pretty the same.
There could be other issues though, you can read on them here

Categories