I have a textarea in my html for user to input some text. I can get it to save into mysql table field with text attribute using php. Before insert into mysql, I will mysql_real_escape_string($data);(for security reason). But when I retrieve it back out from database, I will get
{"bittext":"i
love
mcD"}
With that I will get error:
Error: JSON Parse error: Unterminated string
parse#[native code]
I am not sure how I can reformat it back so that I can parse it to JSON.
Update:
I found out that I did not add json_encode($data) function. Now I can turn
{"bittext":"i
love
mcD"}
into
{"bittext":"i\nlove\nmcD"}
But I am having problem to convert \n to \\n using $data = str_replace(array('\r\n', '\r', '\n'),'\\n', $data);. For some reason \\n is not working. Is there other way to do this?
Update2:
After much of messing around with the code, I finally got it to work:
$je = json_encode($rs,JSON_PRETTY_PRINT);
$nl = array('\r\n', '\r', '\n');
$je = str_replace($nl,'\\n', $je);
My initial issue is when I log it with firephpcore, I can only see \n even after str_replace($nl,'\\n', $je). But as I do more test and found out it actually already work even though it did not display well in console.
From the documentation for mysql_real_escape_string();
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
Your insert statement will inculde the string '{"bittext":"i \\nlove \\nmcD"}' - notice we are escaping the escape character here, which is what mysql_real_escape_string() does.
Which will insert into your table the string '{"bittext":"i \nlove \nmcD"}' - this is what you should see if you do a select from the mysql client.
Somewhere, either pre-insert, or post-select your code is processing the value and changing '\n', to an actual newline byte, instead of leaving it as the string '\n'.
You could patch this by running;
$data = str_replace(array("\r\n", "\r", "\n"), "\\n", $data);
However, I would recommend you track back through your code to see where in your pipeline escaped strings are getting converted to actuals.
Related
I have a form where the users use TinyMCE to fill out some information, and that form is then POSTed, and stored in a database.
The problem appears to be that mysqli::real_escape_string is turning carriage return line feeds into escaped versions of themselves, and storing them. Well... that is part of the design. But when I re-read the database, and run stripslashes() on the data as it is read from the DB, I get output like this:
Here si some good HTML code
rn
But you can see
rn
that there are annoying
rn
"rn" on blank lines between everything.
How can I store HTML in the DB, and retrieve it without having this \r\n problem?
The original answer is not categorically out of date.
The modern best solution is to use PDO.
$pdo = new PDO($dsn);
$sql = "INSERT INTO posts (`foo`) VALUES (?)";
$stmt = $pdo->prepare($sql);
$values = $_POST['text_area'];
$stmt->execute( [ $values ] );
The simplest solution would be to remove the CRLF from the data first
$str = str_replace("\r\n", "", $str);
Be sure to use double quotes so PHP knows to look for CRLF and not a literal \r\n
Well in documentation it is mentioned that
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
so better replace these strings
and
stripslashes()
returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\) are made into a single backslash ().
I am saving C++ code from a textarea of an HTML form using PHP.
The problem is if my code is like below,
printf("%d\n");
printf("%d\n");
the code that is saved to the file is like this:
printf(\"%d\\n\");\nprintf(\"%d\\n\");
I want the original code to be saved in the file. If I use,
$sourceCode = str_replace('\n',"\n", $sourceCode);
$sourceCode = str_replace('\"',"\"", $sourceCode);
the result is like below (saved in the file):
printf("%d\
");printf("%d\
");
It is clear that replacing \n in the source code replaces all the HTML created \n along with the \n that user gave as input (the original text). The only difference is user's input has an additional \ before the \n, that is \\n.
How can I resolve the problem such that only the implicit escape characters will be replaced, but the explicit escape characters, that the user wrote himself, will not be changed?
As mentioned by KenB, we need to see the PHP code that you are using to process the form input.
Processing Form Input
It looks to me like addslashes has been used on the form input.
If you are doing that in your code, don't. This is not the proper way to process form input. Instead, you should use the correct function (such as htmlspecialchars or mysqli_real_escape_string) to escape the input before you use it. Read about addslashes.
If you are using an older version of PHP where magic_quotes_gpc is on by default, then you should fix that. Read about 'Disabling Magic Quotes'.
Stripping Out the Slashes
If you have no control over the code that is adding the slashes, then you can remove them with a simple PHP function called stripslashes.
$sourceCode = stripslashes($sourceCode);
Read about stripslashes.
Understanding Escape Sequences
Your str_replace code shows a lack of understanding about escape sequences and/or a lack of understanding about single vs double quotes.
In the following code, a literal \n is replaced with a line break. With the double quotes, PHP interprets the \n as an escape sequence rather than a literal string.
$sourceCode = str_replace('\n',"\n", $sourceCode);
What you want is to replace a literal \\n with a literal \n. Note that to specify a literal backslash it must be doubled; hence the triple backslash you see below.
$sourceCode = str_replace('\\\n', '\n', $sourceCode);
And although this next line accomplishes what you wanted...
$sourceCode = str_replace('\"',"\"", $sourceCode);
...it could have been written differently. The following code is easier to read, saves you having to escape the literal ", and doesn't require PHP to interpret the string.
$sourceCode = str_replace('\"', '"', $sourceCode);
I've given the above code as examples to explain how PHP interprets escapes sequences, but don't use them. Either avoid adding the slashes in the first place or strip them using the proper function, as explained in the first part of this answer.
Read more about escape sequences and quoting strings.
The Literal \n Between Lines
I'm not sure what you are doing to add the literal \n between the lines. We'd need to see your code. But to remove it after the fact, you could try the following
$sourceCode = str_replace(';\n', ";\n", $sourceCode);
Of course, then you'd likely need to correct other C++ end-of-line sequences. So it is better to not add it in the first place.
I have a textarea submitting to my database on a website that is properly working. But when I generate a CSV (via PHP) from my database, all line breaks will mess up with the resulting CSV. Any CSV reader will interpret the line break from the input into a new line.
I have tried the following approaches:
Encapsulating the fields in quotation marks.
This:
$field = str_replace(array('\n', '\r', '\r\n', '\n\r'), ',', $original_field);
Also this:
$field = strip_tags(nl2br($original_field));
Combining all approaches above.
Anyhow, the ending result will still be a messed up CSV that will break on any line break inputted by user. I have managed to block new line breaks from the text area, but there's a lot of legacy submissions that need me to fix this on the CSV side as well.
Why is it not working? How can I fix this issue?
Before accepted answer (of user user1517891) is not correct, it will replace in string twice, when there is \r\n... It will replace it as two commas ,. First it will replace \r => ,, then \n => ,.
You need to use it in different order, as:
$field = str_replace(array("\r\n", "\n\r", "\n", "\r"), ',', $original_field);
Use double quotes:
$field = str_replace(array("\n", "\r", "\r\n", "\n\r"), ',', $original_field);
I'd suggest using preg_replace() for this rather than str_replace(). The reason is that there may be multiple newlines and combinations of \r and \n, and I would expect that you'd want to replace them all with just a single comma.
I'd also suggest using trim() to remove trailing blank lines.
$field = preg_replace('/[\n\r]+/', ',', trim($original_field));
You have to put \n and similar tags in double quotes otherwise they will be treated as simple strings and not as linebreaks.
I want to replace linebreaks with ' ' in PHP. Somehow I can't get it to work on this json encoded string [[0,"Hello World"],[1,"s\n"]] with $x = preg_replace('/\r\n|\r|\n\r|\n/m', ' ', $x);.
I'm out of ideas. And i know that the php code works with none-json encoded strings. Any ideas to fix this problem
Forgot this:
When I input the string as $xthe function or php code returns the same string. Instead of replacing \n with ' '.
I have also tried all relevant problems in Stackoverflow. none of them successful
preg_replace will try to parse the '\n' as an actual newline character, so you need some more escaping in there.
$x = preg_replace('/\\\r\\\n|\\\r|\\\n\\\r|\\\n/m', ' ', $x);
This is all kind of ugly though. Is there a reason you can't do a replace in the actual decoded strings instead?
"replace newline" seems to be a question asked here and there like hundred times already. But however, i haven't found any working solution for myself yet.
I have a textarea that i use to save data into DB. Then using AJAX I want to get data from the DB in the backend that is in TEXT field and to pass it to frontend using JSON. But pasing JSON returns an error, as new lines from DB are not valid JSON syntax, I guess i should use \n instead...
But how do i replace newlinew from DB with \n?
I've tried this
$t = str_replace('<br />', '\n', nl2br($t));
and this
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\n", $t);
and using CHAR(13) and CHAR(10), and still I get an error
the new line in textarea is equivalent to, i guess
$t = 'text with a
newline';
it gives the same error. And in notepad i clearly see that it is crlf
You need to escape all the characters that have a special meaning in JSON, not only line feeds. And you also need to convert to UTF-8.
There's no need to reinvent the wheel, json_encode() can do everything for you.
Prfff... >_< silly me
I've lost another slash before replacing with \n
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\\n", $t);