Showing multiple lines within textarea after using mysql_real_escape_string - php

I am trying to protect against sql injections by using mysql_real_escape_string before inserting data to the database:
$data=mysql_real_escape_string($_POST['data']);
Now, the data is stored as such:
That\\\'s an apostrophe.\r\n\r\nThis new line isn\\\'t displaying properly!
So, I am trying to get it to display correctly inside of a textarea after pulling it back out of mysql:
$data = nl2br($data);
For whatever reason, this does NOTHING. I've even tried str_replace to replace the \r\n's with a <br>, but then the <br> just displays within the textarea.
How do I get what's in my mysql to display as:
That's an apostrophe.
This new line isn't displaying properly!

The Best Solution..
$data= mysql_real_escape_string($_POST['data']); (You can insert it in your database if you want)
echo stripslashes(str_replace('\r\n',PHP_EOL,$data)); (The output is exactly as your input was)

Actually using mysql_real_escape_string doesn't fully protect you from SQL Injection attack.
See here SQL injection that gets around mysql_real_escape_string()
The best way to do is to use PDO or MySQLi.
See here Best way to prevent SQL injection?

you probably have magic_quotes turned on,
check it with
echo get_magic_quotes_gpc()
or else you will double quote
"Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically. "
by the way, it's not a good ideia to use magic_quotes, try using one of this classes.
PDO http://br2.php.net/manual/en/book.pdo.php
or mysqli http://br2.php.net/manual/en/book.mysqli.php

Related

When I update an sql table row with a content "=" there runs an error

I want to run this:
UPDATE users SET about="$about" ;
but when my $about contains =, the script makes a mistake and do something like this:
$about="<img src=somevalue.jpg />";
The script adds this in the database:
<img src
and nothing more.
try it by using double single quotes.
$about = '<img src=somevalue.jpg />';
$query = "UPDATE users SET about='$about'";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
This is called 'sql injection'. You have to take care of that anyway, so google it.
You have to escape all input you want to use inside statements, anything can happen otherwise. Best is not to use statements constructed by simply including variable content, but use a better engine. Take a look at PDO and the way it works. You "prepare" a statement and hand over parameters as an array. PDO takes care to cleanly escape as required. Much safer that way.
The issue is with putting quotes around string. I'm not very familiar with how php replaces variables in strings but you can try following for MS SQL server:
Set about ="'$about'"

Do I need to use addslashes() when backing up database?

I am using the code shown here, it uses addslashes() on the data fetched from the database before saving to file.
$row[$j] = addslashes($row[$j]);
My question is why and do I need to use this? I thought you would do this when saving to the database not the other way round. When I compare the results from the above script with the export from phpMyAdmin, the fields that contain serialized data are different. I would like to know if it would cause any problems when importing back into the database?
Script:
'a:2:{i:0;s:5:\"Hello\";i:1;s:5:\"World\";}'
phpMyAdmin Export:
'a:2:{i:0;s:5:"Hello";i:1;s:5:"World";}'
UPDATE
All data is escaped when inserting into the database.
Change from mysql to mysqli.
SQL file outputs like:
INSERT INTO test (foo, bar) VALUES (1, '\'single quotes\'\r\n\"double quotes\"\r\n\\back slashes\\\r\n/forward slashes/\r\n');
SOLUTION
Used $mysqli->real_escape_string() and not addslashes()
inserting to db
When inserting data to a MySQL database you should be either using prepared statements or the proper escape function like mysql_real_escape_string. addslashes has nothing to do with databases and should not be used. Escaping is used as a general term but actually covers a large number of operations. Here it seems two uses of escaping are being talked about:
Escaping dangerous values that could be inserted in to a database
Escaping string quotes to avoid broken strings
Most database escaping functions do a lot more than just escape quotes. They escape illegal characters and well as invisible characters like \0 ... this is because depending on the database you are using there are lots of ways of breaking an insert - not just by adding a closing quote.
Because someone seems to have missed my comment about mentioning PDO I will mention it again here. It is far better to use PDO or some other database abstraction system along with prepared statments, this is because you no longer have to worry about escaping your values.
outputting / dumping db values
In the mentioned backup your database script the original coder is using addslashes as a quick shorthand to make sure the outputted strings in the mysql dump are correctly formatted and wont break on re-insert. It has nothing to do with security.
selecting values from a db
Even if you escape your values on insert to the database, you will need to escape the quotes again when writing that data back in to any kind of export file that utilises strings. This is only because you wish to protect your strings so that they are properly formatted.
When inserting escaped data into a database, the 'escape sequences' used will be converted back to their original values. for example:
INSERT INTO table SET field = "my \"escaped\" value"
Once in the database the value will actually be:
my "escaped" value
So when you pull it back out of the database you will receive:
my "escaped" value
So when you need to place this in a formatted string/dump, a dump that will be read back in by a parser, you will need to do some kind of escaping to format it correctly:
$value_from_database = 'my "escaped" value';
echo '"' . $value_from_database . '"';
Will produce:
"my "escaped" value"
Which will break any normal string parser, so you need to do something like:
$value_from_database = 'my "escaped" value';
echo '"' . addslashes($value_from_database) . '"';
To produce:
"my \"escaped\" value"
However, if it were me I'd just target the double quote and escape:
$value_from_database = 'my "escaped" value';
echo '"' . str_replace('"', '\\"', $value_from_database) . '"';
I think you are mixing two problems. The first problem is SQL Injection and to prevent this you would have to escape the data going into the database. However by now there is a far more better way to do this. Using prepared statements and bound parameters. Example with PDO:
// setup a connection with the database
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// run query
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array(':name' => $name));
// get data
foreach ($stmt as $row) {
// do something with $row
}
The other thing you would have to worry about it XSS attacks which basically allows a possible attacker to inject code into your website. To prevent this you should always use htmlspecialchars() when displaying data with possible information you cannot trust:
echo htmlspecialchars($dataFromUnsafeSource, ENT_QUOTES, 'UTF-8');
All data is escaped when inserting into the database.
When using prepared statements and bound paramters this isn't needed anymore.
Should I use addslashes() then use str_replace() to change \" to "?
addslashes() sounds like a crappy way to prevent anything. So not needed AFAICT.
Another note about accessing the database and in the case you are still using the old mysql_* function:
They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is a good PDO tutorial.
You should store data without modifying them.
You should perform the needed escaping when outputting the data or putting them "inside" other data, like inside a database query.
just use mysql_escape_string() instead of addslashes and ereg_replace as written in david walsh's blog.
just try it it'll be better. :)

Problems with mysql insert

My php script won't work if i try to insert into database something in Saxon genitive (for example value "mike's" won't be inserted).
PHP code is plain and simple:
"INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(".$idUser.",'".$LinkName."',".$LinkID.",".$number.",NOW());"
Everything works great until "$LinkaName" get some value with "special character". How to put values like "mike's", "won't" etc. into MySql database?
You need to escape these strings properly. In addition, the technique that you're using right now exposes you to an SQL injection attack.
The PHP docs for mysql_real_escape_string gives a good example of what you should do:
// Query
$query = sprintf("INSERT INTO cache (id,name,LinkID,number,TChecked) VALUES(%d,'%s',%d,%d,'%s');",
mysql_real_escape_string($idUser),
mysql_real_escape_string($LinkName),
mysql_real_escape_string($LinkID),
mysql_real_escape_string($number),
mysql_real_escape_string(NOW()));
You must escape them first, otherwise you generate an invalid query. The single quote matches the single quote at the start of the string.
$LinkName = mysql_real_escape_string($LinkName);
You can also use prepared statements to bind parameters to the query instead of concatenating and sending a string (use the PDO or mysqli libraries instead of the mysql lib).
You need to use mysql_real_escape_string() on those values.
Also make sure if you are not quoting those other variables, to cast them to integer (the only reason why you wouldn't quote them).
If you're using mysqli or PDO and not the standard extension, you can use a prepared statement instead of escaping.

Why does my mysql_real_escape_string not work?

I have read many about SQL-Injection. But it does not work with this code:
$inputform= $_GET["password"];
$query = "INSERT INTO user(password) VALUES ('".mysql_real_escape_string($inputform)."')";
For example I use this example: O'Conner. When I submit it and look in my table there is O'Connor and not O\'Conner.
thanks
The quote is escaped so that MySQL doesn't interpret it as a string delimiter. The backslash doesn't get stored in the database, and it's not supposed to either. What you're seeing is the correct, expected and documented behaviour.
The best solution, BTW, is to use PDO and parametrized queries.
mysql_real_escape_string() escapes the value so that the SQL parser for MySQL can interpret the value correctly when it stores the value, it is not actually stored in the database as an escaped string
If you get O'Connor in your table, it's working properly. But try echo $query and you'll see the results of the escaping.
It works just fine! There shouldn't be "O\'Conner" in your database, just in the query. If it didn't work, your query wouldn't succeed, because the ' in O'Conner would ruin your query.
When you look in the table, it should be O'Connor - that means the string was escaped properly in the SQL. If it hadn't been escaped by mysql_real_escape_string, you probably would have ended up with a syntax error.
The query would end up as:
INSERT INTO user(password) VALUES ('O'Connor)
If you want the backslashes in the DB, try using addslashes before you pass it to mysql_real_escape_string, but you probably don't.

What characters ARE allowed when querying a mysql database?

I have a textarea in a form, when I enter special characters in it, I get an error in mysql. (when submitting the form to a php-file which does the work of inserting into mysql)
I need to know exactly what characters that aren't allowed, or easier would be, exactly what characters thar ARE allowed, so that I could validate the textarea before submitting.
Does anybody know?
I have tried mysql_real_escape_string() but didn't help...
NOTE: In the textarea, users are supposed to enter some special chars like these:
+ , . ; : - _ space & % ! ? = # * ½ # / \ [ ] ' " < > £ $ €
Probably got them all...
how can I do this?
Thanks
UDPATE
My mysql_query :
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
UPDATE
Mysql error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a"a!a?aa+a-a_a
a/a\a[a]a}a{a&a%a#a#a¨a^a*a*aa,a.a:a;a|a½a
§a' at line 1
A database column can technically hold any of those characters. The problem is that you are not escaping them properly in your query.
One way way to do this using mysql_real_escape_string is as follows:
$sql=sprintf("insert into cars_db (description) values ('%s')",
mysql_real_escape_string($_POST['description']) );
//execute query and show errors that result...
$result = mysql_query($sql);
if (!$result) {
die("Oops:<br>$sql<br>".mysql_error());
}
Another way is to use a library like PDO or ADODb which makes it easier to use prepared statements with placeholders. Such libraries ensure that data injected into queries is properly escaped.
This is good practice not only because it solves your problem, but it also improves the security of your code, since it becomes harder to perform SQL injection attacks.
Another way would be to use prepared statements. This makes sure SQL injection isn't possible.
Instead of escaping characters so as not to trip up your query, why not create a stored procedure with an incoming String parameter. Just pass the form variable's value (or save it to a string) and pass that to the stored procedure.
Do this:
$ad_text = mysql_real_escape_string($ad_text);
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
Read up on mysql_real_escape_string and SQL injection. This is a massive security hole in your application.
http://us.php.net/mysql_real_escape_string

Categories