How can I resolve single quote problem while I insert? - php

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.

Related

Save to MySQL serialized info with quotes

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

Backslash not getting formatted with addslashes function + php

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.

Using stripslashes after mysql_real_escape_string

I have to escape some inputs on a form. I used mysql_real_escape_string to escape the value but it adds a lot slashes with value inside database, the reason is i have an apostrophe in my input let us say exp's.
Now to get rid of slashes, I use stripslashes after mysql_real_escape_string and then data goes to database successfully and don't see any apostrophe with value in database.
$name = mysql_real_escape_string(trim($_POST['userame']));
$name = stripslashes(stripslashes($userame));
// then data goes to db successfully without apostrophe
I just wanted to confirm, is this correct way of escaping the input value? Thanks
Dayan
Disabling Magic Quotes
mysql_real_escape_string(stripslashes($_POST['username']));
No it's not. Check your php.ini for the magic_quotes_gpc setting. If you can't disable it use stripslashes BEFORE using mysql_real_escape_string. The link has a method to strip it globally from $_POST, $_GET and $_COOKIE. Or even better, use prepared statements with PDO
If you have magic_quotes_gpc enabled you should use the stripslashes() function before escaping - otherwise you will escape twice, thus loads of slashes.
http://se.php.net/manual/en/function.mysql-real-escape-string.php

How to submit a Quote (') sign in SQL

I've made following protection for my variables:
$ad_title=htmlentities($ad_title);
$ad_title=mysql_real_escape_string($ad_title);
$ad_title=stripslashes($ad_title);
But every time I try to submit a string that contains the quote sign (') - everything after it is recognized as bad SQL query.
Can anyone please let me know what I missed?
I know mysql_real_escape_string should fix it but it doesn't.
Your problem is that stripslashes is UNDOING what mysql_real_escape_string does.
e.g.
starting out with: Miles O'Brien
after m_r_e_s(): Miles O\'Brien
after strip_slashes: Miles O'Brien
Your call after mysql_real_escape_string to stripslashes is effectively canceling it out.
Also, you should be escaping your stuff for html right before you output it, not when you store it in your database.
Alternately, you can use prepared statements, though I'm feeling to lazy to explain that in this answer. (There's millions of posts on SO about it.)
Remove the third line from the code.
$ad_title=htmlentities($ad_title);
$ad_title=mysql_real_escape_string($ad_title);
$ad_title=htmlentities($ad_title);
You can that (immediately) before inserting into an HTML document, not a database … but htmlspecialchars should be sufficient.
$ad_title=mysql_real_escape_string($ad_title);
You can do that (immediately) before mashing together some strings into an SQL statement destined for MySQL … buy you are much better off using prepared statements and bound arguments.
$ad_title=stripslashes($ad_title);
Do that … umm … maybe if you are stuck on a server that has Magic Quotes turned on … but before you do any escaping … and only if you can't turn Magic Quotes off.
Certainly don't do it after you run mysql_real_escape_string as it (largely) reverses the effect of it!
You added the line
$ad_title=stripslashes($ad_title);
which should not be used. You are basically stripping the sql injection protection with that line. remove the line and it should be fine.
<?php
//This should be called first, but ONLY if it is required, or it will corrupt your data.
//This must be done before you manipulate the data in any other way.
//Generally, this is used on the data if your server has magic quotes on.
//I've added code to detect if it is on or not.
$ad_title = (get_magic_quotes_gpc()) ? stripslashes($ad_title) : $ad_title;
//This line is fine, but only do it if you know it is necessary, because it is changing your data.
//If you are doing it just because you were receiving an SQL error, I would recommend you comment this out.
$ad_title = htmlentities($ad_title);
//This should be the last thing you do to your data before using it in SQL.
//This will take care of all required escaping, and protect you from SQL injection.
$ad_title = mysql_real_escape_string($ad_title);
?>

SQL Injection, Quotes and PHP

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.

Categories