Unexpected characters from escaping apostrophes - php

I created a form that takes a block of text and inserts it into an SQL database. I kept getting SQL errors when the user used single quotes. I added the addslashes() function and everything worked out fine. But according to w3, php should already be doing this. Further, when I retrieve the text from the database, all the apostrophes are replaced with � character.
Does anyone know what's happening? I don't even know where to begin.

Use these functions to insert data in db or out from db
These will solve the problem of single quote or double quotes and all special charters.
function DBin($string)
{
return trim(htmlspecialchars($string,ENT_QUOTES));
}
function DBout($string)
{
$string = trim($string);
return htmlspecialchars_decode($string,ENT_QUOTES);
}

Thanks everyone.
mysql_escape_string() worked. For the record, addslashes() was turning apostrophes into backticks. The problem

Related

Cannot replace carriage return and new line in php

I get a string from the frontend which has a line break in it. It is saved in an array which looks like this:
[address] => Array (
[0] => Foo
Bar
)
I then use json_encode() on the array before writing it into the SQL DB:
$string = json_encode( $string, JSON_UNESCAPED_UNICODE );
This turns the array into:
{"address":["Foo\r\nBar"]}
Unfortunately the DB doesn't like \r or \n if not escaped, so it gets rid of the \r and \n.
So the first question is, is there a function that I can use to properly escape the string, so it can be written properly into the DB without losing the line break?
I didn't find any function for that, so I tried to use str_replace to just replace the \r\n with \\n. The function is:
$string = str_replace(["\r\n","\r","\n"], "\\n", $string);
This however does not work. I don't know why. The function itself works, as I tried to replace only "n" with "bla" and it worked. However the moment I try to replace the backslash it does not find anything to replace. I don't know if some "special" backslash character is used here or what else could be going on here.
This is driving me nuts, seriously. So I hope somebody can help me out. Thanks in advance.
Problem :
Your str_replace is not working because you are using double quotes.
Solution :
You should replace your double quotes with single quotes and then the magic will happen :D
$string = str_replace(['\r\n','\r','\n'], '\\n', $string);
EXTRA USEFUL INFORMATION : For more you should take a look at for details as it's useful to get to know the difference between double quotes and single quotes as:
What is the difference between single-quoted and double-quoted strings in PHP?
It depends on how you insert the string into the DB. However you do it, you need to escape it properly.
If you're using PDO, you can achieve this like this:
$conn = new PDO(.....);
$sql_str = $conn->quote($string);
$conn->exec("INSERT INTO table (str_value) {$sql_str}");
Or, better use a prepared statement:
$conn = new PDO(.....);
$stm = $conn->prepare("INSERT INTO table (str_value) :value");
$stm->execute(array(':value' => $string));
Hope that works.
Storing JSON directly in a database? Yeuch!
However if you really must do it, then why do you feel the need to change the representation of the data? When you run it back through a JSON decoder you wil get the original data back. The problem is only how to get it into a safe format for insertion into your database.
That you have created this from a PHP array implies you've got NO EXCUSE for not checking the content of the data before you save it (not that writing data supplied directly from Javascript is in any way valid or forgiveable).
is there a function that I can use to properly escape the string
Yes, there are several - but you've not told us which API you are using. This is not some magical trick to solve the problem you currently find yourself in - escaping any data you write to your database properly is essential to prevent SQL injection.
In addition to the PDO methods mentioned by Alex, you can do it in the (deprecated) mysql extension using mysql_escape_string/mysql_real_escape_string or in mysqli procedural code with mysql_escape_string / mysqli_real_escape_string or msqli_prepare + mysqli_bind_param. The mysqli functions also have object oriented representations.

How to check a string is escaped twice or not

Is is possible to find a string is escaped twice or not using SQL Query (REGEXP) or using PHP?
Please help me on this. I tried more to find it but I'm not getting it anywhere.
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
$escaped_item_twice = mysql_escape_string($escaped_item);
Here i need to find out that $escaped_item_twice is escaped twice. by their result string which is stored in db already. (i.e) i already stored some strings in db with double escape. I want to get those things and to use stripslashes() on that data. How can i get that data?
You cannot make a difference. Escaping is nothing more than adding some \s (in this case). It leaves no other trail. You cannot tell whether double escaping occurred or you simply wanted to escape an escape character (\\) that was meant to be there.

line breaks showing up as \r\n in textarea

I am trying to display a data into textarea which is fetched from tables that i have submitted via another form. The issue comes up when a new line is entered.
The data getting displayed in the textarea is as
lin1\r\nlin2
it should be like
lin1
lin2
I have tried nl2br but it does not work as expected.
How can i make things optimized. Thanks
This problem can be solved using stripcslashes() when outputting your data.
Please note that the method above is different from stripslashes() which doesn't work in this case.
I tried using nl2br but it wasn't sufficient either.
I hope str_replace saves you.
<?php
$str='lin1\r\nlin2';
$str=str_replace('\r\n','<br>',$str);
echo $str;
OUTPUT:
lin1
lin2
This is a common question and the most common answers are ln2br or str_replace.
However this is just creating unnecessary code.
In reality the problem is pretty much always that you have run the data through a mysql escape function before displaying it. Probably while you were in the process of saving it. Instead, escape the data for saving but display an unescaped version.
<?php echo str_replace('\r\n', "\r\n", $text_with_line_breaks); ?>
See single quotes & double quotes this is a trick.
A perfect solution for newbies.
you overdo quote in insert/update statement
This problem in you case you can solve doing next
<?php
$str = 'lin1\r\nlin2';
$solved_str = str_replace(array("\\r","\\n"), array("\r","\n"), $str);
var_dump($str,$solved_str);
But you need to check insert/update statement on over quotation escape symbols
I would recommend using double quotes for \r\n such as "\r\n". I've never had it work properly with single quotes.
For non- textarea use this function
function escapeNonTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("<br>","<br","<br>"),$string);
return $string;
}
For text area use this function
function escapeTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("\n","\r\n","\r"),$string);
return $string;
}
call appropriate function and pass argument

Escaped value ('\s) in database

I'm using codeigniter, and what I do is basically:
$val = $this->db->call_function('real_escape_string', $this->input->post('name'));
this is all I do on data before putting into database. And when someone enters value like O'hara, in database it will appear like O\'hara
So, I guess I can string slashes on output, but is this usual way of escaping and storing data in database?
SOLVED
Active Records escapes the query, so I do double escaping, with 'real_escape_string' function as well
So I guess I don't need to use real_escape_string at all, active records does this
The '\' is called an escape character and must be used so the next character after it (in your case ') won't interfere with the SQL statement. However, if you're using CI, it should take care of all of this for you. There's an 'HTML helper' that I believe you can use to format or take out the slashes on outputted text. Even then, but I could be wrong, when outputting values from a DB in CI, the slashes will automatically be stripped.
Escaping quotes and special characters is both regular practice and expected for record storage as it helps to ensure that your code can be accurately stored and extracted.
Escaping the strings for the SQL query is so that you can get the actual values into the database.
The value in the SQL query will look like O\'hara but the value that ends up in the database is O'hara.
So, you don't have to do anything at all when you display the value. Except escaping it for the environment where you display it of course. If it's displayed in a HTML document, you would HTML encode it. This will not change the apostrope ('), but it will change other characters, like < and >.
use directly
$val = real_escape_string($this->input->post('name'));

KO3/Kohana3: How do we escape quotes (double and single) before saving to db with ORM using values()?

I allow users to submit a question, and they should be able to have single quotes in their title.
Currently, if a title contains a single quote, it will submit properly.
$question->values($post_data); $question->save();
Any ideas on how I can set Kohana to escape that single quote / escape my information automatically? I would like to avoid having to addslashes() every input and removeslashes() every display...
Thank you so much, SO community!
(This question is crossposted at http://forum.kohanaframework.org/comments.php?DiscussionID=6525)
Actually, you should never use addslashes() to escape DB values at all. Especially not in Kohana, since values are "escaped" while being saved ( example you're giving is ORM one, you can always mess up a custom DB query to get a MySQL injection / broken query ).
If you don't want something to get escaped, wrap it in DB::expr() ( so it'll return an instance of Database_Expression, which doesn't get automatically escaped ).
To escape a value manually, use Database::quote() (not static, call it through your Database object, e.g. $db->quote($value) ).
But! Kohana has a problem with backticks (`). This is a system's symbol.
elseif(preg_match('/\`/', $value))//if a backtick
{
return str_replace('\'', '', $value);//'value'=>value!!!
}
return $this->escape($value);

Categories