mysql_real_escape_string conversion to mysqli - php

Ok I would like to know how you convert this mysql code into mysqli.
function protect($string) {
return mysql_real_escape_string(strip_tags(addslashes($string)));
}
I know you change mysql to mysqli but it asks for 2 parameters this worked with mysql so I would like to see it in mysqli
also I haven't yet found someone on stackoverflow with a question about the new mysqli version so I wasn't able to find out myself

It is better not to use it at all!
mysql_real_escape_string() was a hack which was used to prevent SQL injection, and it didn't even do that 100%. This function was never meant to protect anything. It is a simple string formatting function.
mysqli_real_escape_string() is yet another hack to make the transition easier. Although, at the time of writing this post mysql_* has been deprecated for so long, that no one should have any excuse to use some kind of shim for transitioning, because everyone should already be using MySQLi with prepared statements or even better PDO.
As for strip_tags() and addslashes() they are useless in this context and only mutilate your data. Don't use them.
To protect against SQL injection, one should use prepared statements and ensure that no variable input is inserted into SQL directly.
For example:
$stmt = $mysqli->prepare('SELECT columnA FROM tableB WHERE columnC=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();

This function is a bad idea.
Using strip_tags() and addslashes() indiscriminately on all incoming data needlessly mutilates it, with zero added security.
To feed data into the database, use only the string escaping function, real_escape_string().
To display data from the user on a HTML page, strip the tags then or use htmlspecialchars() to avoid any scripting attacks.

Try like this:
$mysqli = new mysqli("host", "username", "pword", "db");
function protect($string) {
return $mysqli->real_escape_string(strip_tags(addslashes($string)));
}
EDIT
$link = mysqli_connect("localhost", "root", "", "aaa");
$city = "'s Hertogenbosch";
$city = mysqli_real_escape_string($link, $city);
echo($city);

Related

Effective protection function against SQL injection

I found this sanitizing function in a free software:
function VerifChamps($valeur)
{
$verif = (get_magic_quotes_gpc()) ? htmlentities($valeur, ENT_QUOTES) : addslashes($valeur);
return $verif;
}
The query is then done like this:
$login=VerifChamps($_POST['name']);
mysql_select_db(..., ...);
$query = sprintf("SELECT * FROM table WHERE login='%s'", $login);
$Result = mysql_query($query, $connexion) or die(mysql_error());
$row_RsProf = mysql_fetch_assoc($Result);
mysql_free_result($Result);
How safe is this code? How is it possible to improve it to make it even more secure?
EDIT: the server is running PHP v5.2.13, with Magic Quotes turned on
The short answer is that it's not safe at all.
Here's what's wrong with it...
You're checking get_magic_quotes_gpc, which has been removed from PHP for years
You're using htmlentities to encode the string if magic quotes is on, but not if it's off (way to corrupt your data)
Why are you using htmlentities at all to send data to the database? It doesn't prevent sql injection at all.
addslashes doesn't take the client connection character encoding into account when escaping your data (which makes it very unsafe)
You're returning an undefined variable (i.e. NULL) making the entire function useless
Also, mysql was deprecated and has been removed from PHP 7. Use the newer MySQLi extension instead.
You can simply replace your entire function with the functionality provided by newer database APIs like MySQLi and PDO which offer prepared statements and parameterized queries, which are already proven to be reliable and secure. The code you're providing in your example here is clearly ancient and very insecure.
For many days, i am using mysqli_real_escape_string function. It's a good function to avoid sql injection.
And, please avoid mysql extension.This extension will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
You want to use prepared statements
http://www.w3schools.com/php/php_mysql_prepared_statements.asp

PDO without mysql_real_escape_string and bindValue

I'm relatively new to PDO and i have written the following block of code:
$id = $_GET['id'];
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
foreach($db->query("SELECT id,name FROM names where id = '$id' ") as $row) {
echo "<p>", ($row['name']), "<br>";
}
My uncertainties are:
is it safe to OMIT mysql_real_escape_string in the first line since i'm using PDO
is it safe to run the query as above without using bind values.
Thanks
No, this is not safe. PDO doesn't magically escape your queries for you. Your code, as shown, is wide open to SQL injection.
If you are using variables in your query, don't use ->query. Do not try to escape them yourself. You should be using prepared statements. That's the way to be safe.
$stmt = $db->prepare('SELECT id,name FROM names where id = ?');
if($stmt->execute(array($id))){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<p>", ($row['name']), "<br>";
}
}
So, yes, you need to use bindParam, or execute, as shown.
P.S. mysql_real_escape_string is only for the (deprecated) mysql_ extension. It doesn't work with PDO.
to answer your questions,
it is safe to omit mysql_real_escape_string as long as you use bindings (well.... you can't use mysql_real_escape_string with PDO anyway)
Nope. It is absolutely unsafe. doesn't matter whether you are using PDO or not.

What is the PDO equivalent of function mysql_real_escape_string?

I am modifying my code from using mysql_* to PDO. In my code I had mysql_real_escape_string(). What is the equivalent of this in PDO?
Well No, there is none!
Technically there is PDO::quote() but it is rarely ever used and is not the equivalent of mysql_real_escape_string()
That's right! If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.
# Example:
Below is an example of a safe database query using prepared statements (pdo)
try {
// first connect to database with the PDO object.
$db = new \PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
// if connection fails, show PDO error.
echo "Error connecting to mysql: " . $e->getMessage();
}
And, now assuming the connection is established, you can execute your query like this.
if($_POST && isset($_POST['color'])){
// preparing a statement
$stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");
// execute/run the statement.
$stmt->execute(array($_POST['color']));
// fetch the result.
$cars = $stmt->fetchAll(\PDO::FETCH_ASSOC);
var_dump($cars);
}
Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.
It is worth noting that you should pass a charset=utf8 as attribute, in your DSN as seen above, for security reasons, and always enable
PDO to show errors in the form of exceptions.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.
Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ] as described in this answer
But, using prepared statements as shown above will always be safer, than using any of the functions that start with mysql_
Good reads
PDO Tutorial for MySQL Developers
There is none*! The object of PDO is that you don’t have to escape anything; you just send it as data. For example:
$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;');
$query->execute([':name' => $username]); # No need to escape it!
As opposed to:
$safe_username = mysql_real_escape_string($username);
mysql_query("SELECT * FROM users WHERE username = '$safe_username' LIMIT 1;");
* Well, there is one, as Michael Berkowski said! But there are better ways.
$v = '"'.mysql_real_escape_string($v).'"';
is the equivalent of $v = $this->db->quote($v);
be sure you have a PDO instance in $this->db so you can call the pdo method quote()
There is no need of mysql_real_escape_string in PDO.
PDO itself adjust special character in mysql query ,you only need to pass anonymous parameter and bind it run time.like this
Suppose you have user table with attribute name,email and password and you have to insert into this use prepare statement like this
you can pass name as => $name="Rajes'h ";
it should execute there is no need of equivalent of mysql_real_escape_string
$stmt="INSERT into user(name,email,password) VALUES(:name,:email,:password)";
try{
$pstmt=$dbh->prepare($stmt);//$dbh database handler for executing mysql query
$pstmt->bindParam(':name',$name,PDO::PARAM_STR);
$pstmt->bindParam(':email',$email,PDO::PARAM_STR);
$pstmt->bindParam(':password',$password,PDO::PARAM_STR);
$status=$pstmt->execute();
if($status){
//next line of code
}
}catch(PDOException $pdo){
echo $pdo->getMessage();
}
The simplest solution I've found for porting to PDO is the replacement for mysql_real_escape_string() given at https://www.php.net/manual/en/mysqli.real-escape-string.php#121402. This is by no means perfect, but it gets legacy code running with PDO quickly.
#samayo pointed out that PDO::quote() is similar but not equivalent to mysql_real_escape_string(), and I thought it might be preferred to a self-maintained escape function, but because quote() adds quotes around the string it is not a drop in replacement for mysql_real_escape_string(); using it would require more extensive changes.
In response to a lot of people's comments on here, but I can't comment directly yet (not reached 50 points), there ARE ACTUALLY needs to use the $dbh->quote($value) EVEN when using PDO and they are perfectly justifiable reasons...
If you are looping through many records building a "BULK INSERT" command, (I usually restart on 1000 records) due to exploiting InnoDb tables in MySQL/Maria Db. Creating individual insert commands using prepared statements is neat, but highly inefficient when doing bulk tasks!
PDO can't yet deal with dynamic IN(...) structures, so when you are building a list of IN strings from a list of user variables, YOU WILL NEED TO $dbh->quote($value) each value in the list!
So yes, there is a need for $dbh->quote($value) when using PDO and is probably WHY the command is available in the first place.
PS, you still don't need to put quotes around the command, the $dbh->quote($value) command also does that for you.
Out.
If to answer the original question, then this is the PDO equivalent for mysql_real_escape_string:
function my_real_escape_string($value, $connection) {
/*
// this fails on: value="hello'";
return trim ($connection->quote($value), "'");
*/
return substr($connection->quote($value), 1, -1);
}
btw, the mysqli equivalent is:
function my_real_escape_string($value, $connection) {
return mysqli_real_escape_string($connection, $value);
}

Escaping Quote for Variable in SQL Call

How do you add a single quote to a variable within a SQL statement? If I put 'jeremy' in place of the '\$user'\ variable it works perfectly. I can't figure out how to escape the quote for the variable in the SQL statement. Thank you for your help.
$resultArticles = mysql_query("SELECT COUNT(id) FROM articleList WHERE user = '\$user'\ ");
$totalArticlesLeaderboard = mysql_result($resultArticles, 0);
echo "<strong>Total Articles: </strong>" . $totalArticlesLeaderboard;
I've tried to find a suitable duplicate of your question, but I only found real dupes which are based on the ancient mysql_* functions. The mysql_* functions (like the ones you are using) are no longer maintained by the PHP commuity (for some time now) and the deprecation process has begun on it. See the red box?
You should really try to pick up the better PDO or MySQLi. Both of these option should be fine. Imho PDO has a better API, but mysqli is more towards mysql (in most cases PDO will do whatever you want to use it for).
With the two "new" API there is also the possibilty to use prepared statements. With prepared statements you should not have to worry about manually escaping values before inserting them into your queries.
An example of this using the PDO API would be:
$db = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('SELECT COUNT(id) FROM articleList WHERE user = :user');
$stmt->execute(array('user' => $user));
As you can see the values are not inserted directly into the query, but instead it uses placeholders. This code will make it impossible for people to inject arbitrary SQL into your query. And also you don't need to do any escaping anymore.
If you need more help in deciding between PDO or mysql check out the docs with more information about it. If you choose PDO you can find a good tutorial on the topic here.
Test this
$resultArticles = sprintf("SELECT COUNT(id) FROM articleList WHERE user='%s",
mysql_real_escape_string($user));
You should be able to just remove the escape characters:
$user = mysql_real_escape_string($user);
$resultArticles = mysql_query("SELECT COUNT(id) FROM articleList WHERE user = '$user'");
If you ever have trouble with variables, you can always just end the string and concatenate. I do this often to avoid confusion:
$user = mysql_real_escape_string($user);
$resultArticles = mysql_query("SELECT COUNT(id) FROM articleList WHERE user = '".$user."'");
As PeeHaa said, make sure you try to use PDO or MySQLi.
Don't forget to escape all user input, or they potentially can destroy your database. If you are using MySQLi, you can use mysqli::real_escape_string. Sanitizing ALL your user data is absolutely essential. DO NOT SKIP THIS!
If the variable $user contains any special characters, it is necessary to escape these, as shown in the first answer. If you don't have the mysql_real_escape_string() function available, use addslashes().

Is this SQL query safe from injection?

The code below is written in php:
$user = addslashes($_POST['user']);
$pwd = addslashes($_POST['pwd']);
$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";
the query will then be sent to mysql
Is there anything more I need to take care of?
Please point out.
No it's not safe, use mysql_real_escape_string at minimum:
$user = mysql_real_escape_string($_POST['user']);
$pwd = mysql_real_escape_string($_POST['pwd']);
And for better security go for prepared statements.
Best Options:
PDO
mysqli
You may ask which one to choose, check out:
What is difference between mysql,mysqli and pdo?
Nope.
The reason is that while a single quote ' is not the only char that break a sql query, quotes are the only chars escaped by addslashes().
Better: use mysql_real_escape_string
$user = mysql_real_escape_string($_POST['user'], $conn);
$pwd = mysql_real_escape_string($_POST['pwd'], $conn);
$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";
Best: use PDO and prepared statements
$stmt = $dbh->prepare("SELECT * FROM userdata WHERE UserName=':user' AND Password=PASSWORD(':pass')");
$stmt->bindParam(':user', $user);
$stmt->bindParam(':pass', $pass);
No. You should not be using addslashes() to escape your data. That's been obsolete for years. You should be either:
using mysql_real_escape_string() as a replacement
using prepared statements with PDO or MySQLi
Plus using MySQL's Password() function is also poor pracdtive. Use hashes with salts. Bcrypt is my recommendation. Also, check out PHPass.
Protecting against SQL injection is easy:
Filter your data.
This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.
Quote your data.
If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.
Escape your data.
Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn't a specific one, addslashes() is a good last resort.
Read more: http://phpsec.org/projects/guide/3.html#3.2

Categories