I am having following php string: "Device/ mo\bile's";
I want to insert it into db and so before insert i am sanitizing it with addslashes function
and sanitization happens but the string is inserted into the db as "Device/ mobile's" ie. backlash vanishes.
I want to retain '\' also.
Anybody suggest how can i do that.
Thanks in advance.
Don't use addslashes for escaping SQL. In fact, don't use addslashes for anything. If you are still using the by now deprecated mysql_* functions, use mysql_real_escape_string. If you're using the newer mysqli_* or PDO extension, use prepared statements. Then all data will be inserted properly. If you use unrelated escaping functions which do not consider to appropriate escaping rules for the language at hand, you won't get the correct results.
Related
I know that the ultimate way is to use mysqli_real_escape_string function. But it is pretty long and for numerical values I often use $value + 0 statement. Is it secure enough?
Yes it is. Don't forget to use "real" which is the new version of mysqli_escape_string ;)
Btw, you should use prepared statement with mysqli:
You can read more about this on: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
This will avoid using mysqli_real_escape_string
for numerical variable mysqli_real_escape_string maybe cant help you
for example in blind sql inejction
i think you can use intval() function for more safety
this link more explain about this function
http://ir2.php.net/intval
be successfull
Trying to save serialized string to SQL, but then i am having problems with unserializing it because of quotes.
Example, string is "te'st", after serialize we have
s:5:"te'st";
But to save it to SQL we need to add slashes, and i am doing
serialize(addslashes($string))
after this, in our MySQL db we have
s:6:"te'st";
And this is the problem. s:6 means we have 6 symbols string, but our "te'st" is only 5, so when we trying to unserialize it, we getting error.
How to solve it? Tried htmlspecialchars and mysql_real_escape_string
Update:
How i use mysql_real_escape_string
mysql_query("INSERT INTO `table`(`string`) VALUES ('" . serialize(array('iId' =>$aSqlResult['typeID'], 'sName' => mysql_real_escape_string($sScanResultLine))) . "')");
You should pass the data through the escape function after the serialization, not before - which is what you are doing now.
$serialized = mysql_real_escape_string(serialize($data));
Use a parameterised query with PDO or MySQLi and you can forget about the escaping altogether.
You're making a mistake I've seen many making. A bit of a fundamental misunderstanding of how escaping functions and should be used.
You cannot simply chain escape functions and end up with something that's perfect for any context. Your mistake is simple..
You're doing two things:
Serializing an object ( a string in this case )
Saving that into the database.
So before you save it to the database, you must make sure that your value is properly escaped. DO THIS WITH MYSQLI! The mysql_ functions are dead.
The equivalent is mysqli::real_escape_string.
But most importantly.. (sorry for dragging this on)..
serialize modifies the output, it can return a whole bunch of things.. quotes, 0x00's and this is not allowed in mysql queries.
So real_escape_string must obviously be the last step! First serialize, and the escape the output of that function. You did the exact opposite.
In your case the mysql_real_escape_string() is the way to go. It have to work, unless you did it somehow wrong (note: you need to be connected to DB before calling that function). And in fact you should use mysqli_ or PDO, not a mysql_ extension which is now deprecated. Using htmlspecialchars() is simply using wrong tool for the task.
Code should be like this:
mysql_real_escape_string( serialize( $string ) );
Currently I use this strategy:
After submitting a HTML form or data sent using jQuery's $.get() or $.post() I need to know what is come and then apply logic on the basis of that.
suppose, I've got $_POST['username'], $_POST['password'] and $_POST['login_submit_button'].
In my processing script file, I do like this:
if(isset($_POST['login_submit_button']) && isset($_POST['username']) && $_POST['username'] != "" && isset($_POST['password']) && $_POST['password'] != "") {
// calling a common function safe_vars() which does
// mysql_real_escape_string(stripslashes(trim($any_variable_need_to_become_safe)))
// and now using the above variables for different purposes like
// calculation, insertion/updating old values in database etc.
}
I know all this logic is wrong or having serious issues, so I want a much-secure and perfect solution instead of this. I welcome to find out vulnerabilities and severe security-bleaches in my strategy. This question can help others too, if answers came more explanatory, this can be informative community wiki.
There is no way to make a generic super "make things safe" function.
mysql_real_escape_string
You shouldn't use this at all. It uses the old mysql API, and assumes you are going to be manually smashing strings together to make SQL. Don't do that. Use PDO or mysqli and a function that deals in prepared queries and bound arguments.
stripslashes
This is an antidote to magic quotes. If magic quotes are not on it will destroy data. Don't use it. Turn magic quotes off instead.
trim
This destroys data. Don't use it unless you really want to remove white space at the start and end of the string.
Escape data for the target language immediately before inserting data into that language.
For SQL, use bound arguments and prepared queries.
For HTML, use htmlspecialchars or a template language that does escaping for you, such as mustache.
Alternatively, (if you want to allow HTML) parse it, generate a DOM, filter it using a whitelist, then serialise it back to HTML.
For JSON, use encode_json
etc.
You only need to stripslashes if you have magic_quotes enabled (use get_magic_quotes_gpc to check)
You should white list filter your POST vars using filter_var or ctype_* or preg_match (as well as checking bound conditions such as length and presence)
Use prepared statements / PDO for your queries to ensure proper escaping
Escape any html output with htmlentities
Nothing is bullet proof, however the above are good practices to avoid SQL injection / XSS.
I'm quite confused now and would like to know, if you could clear things up for me.
After the lateste Anon/Lulsec attacks, i was questioning my php/mysql security.
So, i thought, how could I protect both, PHP and Mysql.
Question: Could anyone explain me, what's best practice to handle PHP and Mysql when it comes to quotes?
Especially in forms, I would need some kind of htmlspecialchars in order to protect the html, correct?
Can PHP be exploitet at all with a form? Is there any kind of protection needed?
Should I use real_escape_string just before a query? Would it be wrong/bad to use it already within PHP (see sanitize_post function)?
Currently i'm using the following function. The function "sanitizes" all $_POST and $_GET variables. Is this "safe"?
function sanitize_post($array) {
global $db;
if(is_array($array)) {
foreach($array as $key=>$value) {
if(is_array($array[$key])) {
$array[$key] = sanitize_post($array[$key]);
} elseif(is_string($array[$key])) {
$array[$key] = $db->real_escape_string(strtr(stripslashes(trim($array[$key])), array("'" => '', '"' => '')));
}
}
} elseif(is_string($array)) {
$array = $db->real_escape_string(strtr(stripslashes(trim($array)), array("'" => '', '"' => '')));
}
return $array;
}
I'm using PHP 5.3.5 with Mysql 5.1.54.
Thanks.
mysql_real_escape_string deserves your attention.
However direct queries are a quagmire and no longer considered safe practice. You should read up on PDO prepared statements and binding parameters which has a side benefit of quoting, escaping, etc. built-in.
BEST practice is always to use prepared statements. This makes SQL injection impossible. This is done with either PDO or mysqli. Forget about all the mysql_* functions. They are old and obsolete.
Question: Could anyone explain me, what's best practice to handle PHP
and Mysql when it comes to quotes?
That's easy: Use prepared statements, e. g. with PDO::prepare or mysqli_prepare.
There is nothing like "universal sanitization". Let's call it just quoting, because that's what its all about.
When quoting, you always quote text for some particular output, like:
string value for mysql query
like expression for mysql query
html code
json
mysql regular expression
php regular expression
For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (always assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode() - only for utf8! I use my function for iso-8859-2
mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
preg_quote()
Don't waste the effort using mysql_real_escape_string() or anything like that. Just use prepared statements with PDO and SQL injection is impossible.
I usually use the PHP functions stripslashes and strip_tags on the variables as they come in via $_POST (or $_GET, depending on what you use) and mysql_real_escape_string during the query. (I'm not sure if this is "right" but it's worked for me so far.) You can also use PHP's built in validate filters to check things like email addresses, url's, data types, etc. PDO is supposedly decent at preventing SQL injection but I haven't had any experience with it yet.
The basic workflow should be
$data = $_POST['somefield which will go into the database'];
... do data validation ...
if (everything ok) {
$escaped_data = escape_function($data);
$sql = " ... query here with $escaped_data ... ";
do_query($sql);
}
Basically, data that's been escaped for database insertion should ONLY be used for database insertion. There's no point in pre-processing everything and overwriting all data with db-escaped values, when only 2 or 3 of 50(say) values actually go anywhere near the db.
Ditto for htmlspecialchars. Don't send data through htmlspecialchars unless it's headed for an HTML-type display.
Don't store data in the DB formatted for one particular purpose, because if you ever need the data in a different form for some other purpose, you have to undo the escaping. Always store raw/unformatted data in the db. And note: the escaping done with mysql_real_escape_string() and company does not actually get stored in the db. It's there only to make sure the data gets into the database SAFELY. What's actually stored in the db is the raw unescaped/unquoted data. Once it's in the database, it's "safe".
e.g. consider the escaping functions as handcuffs on a prisoner being transferred. While the prisoner is inside either jail, cuffs are not needed.
What is the best way to avoid \' while we get the values from PHP post method and want to store in the database. I have used simply , echo $_POST['txtname'];
it produces the output Uncl\'es Jules, if enter name as Uncl'es Jules
Can any one suggest the better way?
This sounds like you have magic_quotes enabled that's why it is escaping data automagically.
You should disable magic_quotes. Here is how you can
Escape data with mysql_real_escape_string() while inserting them
If magic_quotes is not disabled with any reason you can use stripslashes do remove those extra \.
echo stripslashes($data);
http://php.net/manual/en/function.mysql-real-escape-string.php
use mysql_real_escape_string
Try using mysql_real_escape_string().
insert into tblTable1 set field1 = mysql_real_escape_string($_POST['txtname']);
Or mysqli_real_escape_string(), also PDO has matching functions too.
It is escaping unsafe characters to store in the database. You actually want your SQL library to do this. If you do not do this, you are open to SQL Injection, and that's bad. :)
But it seems like you have magic quotes enabled. Do not use that and use mysql_real_escape_string() to escape your data before it is inserted into the database.
What you need to do is revert all escaped characters back when you display your data.