I am using PHP/mysqli to read in comments, but various comments in the table have either a single quote or a double quote.
I am storing the comments in a data-attribute. Using the Chrome console, I can see where the quote is throwing the whole code out of whack.
<?php
echo "<td><a href='' class='comment' data-toggle='modal' data-comment='".htmlentities($row[comment])."'>" . $row[partner_name] . "</a></td>";
?>
As you can see in the code above, I tried to use htmlentities. I also tried addslashes and a combination of the two.
Either way, I still can't get the comment to display properly because of the quote inside the mysql table.
Is there another PHP function that I can use to fix this?
Directly above is a screen shot from the Chrome console. Right after the words POTENTIAL 53 there is a single quote that is throwing my code off. All the other orange text is being read as HTML when it's supposed to be part of the comment.
There has to be a way to read the single quote as part of the string.
Pass the flag, ENT_QUOTES, to your htmlentities function. See http://php.net/htmlentities. This will replace quotes with entified quote and prevent it from breaking out of the data-comment attribute.
Well, there are two problems:
You have to encode stuff, especially quotes:
$text = htmlentities($value, ENT_QUOTES);
The title attribute does not work with newlines, so you will have to deal that. Something like this should do the job:
$text = preg_replace('/\r?\n/', '#xA;', $text);
Try escaping the quotes in your data. Something to this affect:
$pattern = "/\"|\'/";
$replace = '\\\"';
$subject = $row[comment];
$rowComment = preg_filter($pattern, $replace, $subject);
*Tip - You can also filter the data before storing it.
Description: echo $rowComment will produce a string with all quotes escaped;
Related
I am trying to echo a variable that contains a ', however it broke the script. To fix this, I used addslashes();
This is my code
$row["market_hash_name"] = addslashes($row["market_hash_name"]);
echo $row["market_hash_name"];
Now this doesn't break the script, but displays a backslash. How can i not make it display a backslash before the ' without the ' breaking the script.
Edit: I understand it does not break the script, however, it prevents the rest of the jQuery echoed by the php from working properly.
You can use:
echo htmlspecialchars($row["market_hash_name"], ENT_QUOTES);
It will make sure all special characters are converted to HTML entities, so a single quote becomes '
It won't be breaking, if you are just echoing
$row = array(
'market_hash_name' => "hello'world"
);
echo $row['market_hash_name']; // outputs: hello'world
Echoing the word don't doesn't break your script and you can easily echo it when it is stored in a variable but if you want to echo a word without storing it somewhere it needs to be escaped using htmlspecialchars()
I think you have been confused with query and html output. In a query you escape a string twice. for example:
$query = 'I don\'t think so.';
^ first escape for php script
$query = 'I don\\\'t think so.';
^ second escape for mysql
it goes to mysql like this: I don\'t think so.
Also you can use different types of quotations to avoid this 2 step escaping. like:
"I don't think so.";
'I don"t think so.';
For example I want to store the String "That's all". MySQL automatically escapes the ' character. How do I echo that String from the database using php but remove the \ in front of escaped characters like \' ? I would also like to preserve other formatting like new lines and blank spaces.
Have you tried stripslashes(), regarding the linebreaks just use the nl2br() function.
Example:
$yourString = "That\'s all\n folks";
$yourString = stripslashes(nl2br($yourString));
echo $yourString;
Note: \\ double slashes will turn to \ single slashes
You should probably setup your own function, something like:
$yourString = "That\'s all\n folks";
function escapeString($string) {
return stripslashes(nl2br($string));
}
echo escapeString($yourString);
There are also several good examples in the nl2br() docs
Edit 2
The reason your are seeing these is because mysql is escaping line breaks, etc. I am guessing you are using mysql_* functions. You should probably look into mysqli or PDO.
Here is an example:
$yourString = "That's all
folks";
echo mysql_escape_string($yourString);
Outputs:
That\'s all\r\n folks
If you use prepared statements, those characters will not be escaped on insert.
Use stripslashes() to remove slashes if you cannot avoid adding slashes on input.
At first, magic_quotes_gpc escapes the character like ' or ". You can also disable this in your php.ini. But then you should escape the things yourself that no query can get "infected".
Lookup mysql injection for more information.
When the escaped string is been written in your database. The string doesn't contain theses escape charakters and when you output them again. You should see the result as you want it.
Me for myself prefer the method by storing everything without escapes and escape or display things when I output them. You could also easily use an str_replace("\n", "", $text) to prevent newslines are displayed.
Greetings MRu
I have built a search engine using php and mysql.
Problem:
When I submit a word with an apostrophe in it and return the value to the text field using $_GET the apostrophe has been replaced with a backslash and all characters after the apostrophe are missing.
Example:
Submitted Words: Just can't get enough
Returned Value (Using $_GET): Just can\
Also the url comes up like this:search=just+can%27t+get+enough
As you can see the ' has been replaced with a \ and get enough is missing.
Question:
Does anybody know what causes this to happen and what is the solution to fix this problem?
The code:
http://tinypaste.com/11d62
If you're running PHP version less than 5.3.0, the slash might be added by the Magic Quotes which you can turn off in the .ini file.
From your description of "value to the text field" I speculate you have some output code like this:
Redisplay
<input value='<?=$_GET['search']?>'>
In that case the contained single quote will terminate the html attribute. And anything behind the single quote is simply garbage to the browser. In this case applying htmlspecialchars to the output helps.
(The backslash is likely due to magic_quotes or mysql_*_escape before outputting the text. I doubt the question describes a database error here.)
Update: It seems it's indeed an output problem here:
echo "<a href='searchmusic.php?search=$search&s=$next'>Next</a>";
Regardless of if you use single or double quotes you would need:
echo "<a href='searchmusic.php?search="
. htmlspecialchars(stripslashes($search))
. "&s=$next'>Next</a>";
(Notice that using stripslashes is a workaround here. You should preserve the original search text, or disable the magic_quotes rather.)
Okay I forgot something crucial. htmlspecialchars needs the ENT_QUOTES parameter - always, and in your case particularly:
// prepare for later output:
$search = $_GET['search'];
$html_search = htmlspecialchars(stripslashes($search), ENT_QUOTES);
And then use that whereever you wanted to display $search before:
echo "<a href='searchmusic.php?search=$html_search&s=$next'>Next</a>";
Single quotes are important in PHP and MySQL.
A single quote is a delimeter for a string in PHP, for example:
$str = 'my string';
If you want to include a literal quote inside a string you must tell PHP that the quote is not the end of the string. It is escaped with the backslash, for example:
$str = 'my string with a quote \' inside it';
See PHP Strings for more on this.
MySQL operates in a similar way. An example query might be:
$username = 'andyb';
$quert = "SELECT * FROM users WHERE user_name = '$username'";
The single quote delimits the string parameter. If the $username included a single quote, this would cause the query to end prematurely. Correctly escaping parameters is an important concept to be familiar with as it is one attack vector for breaking into a database - see SQL Injection for more information.
One way to handle this escaping is with mysql_real_escape_string().
PHP is echoing JavaScript (I'm using the jQuery library) something like this:
echo 'var users = $("#add").val().split("\n");';
However, the \n is creating a line break in what the echoed script looks like, and therefore breaking the JavaScript. Is there a way to circumvent this?
Many thanks!
The \n is an escape sequence meaning newline. Backslashes are the beginning of escape sequences, to output a backslash then write \\. So you want \\n. Other useful escape sequences include the quote: use \" to put a quote into the string instead of ending the string.
echo "var users = $(\"#add\").val().split(\"\\n\");";
Not sure If you looking for this
echo "<script>alert('Line1\\\\nThis still in Line1')</script>";
I can't get nl2br function to work after fetching data from my database:
$result = mysql_query("SELECT comments..etc.etc..");
while ($row = mysql_fetch_array($result))
{
echo nl2br($row["comments"]);
}
In database row comments:
\r\nThanks,\r\n
OUTPUT:
Same as in DB:
\r\nThanks,\r\n
If I simply test this out like so it works fine:
<?php
$mystring = "\r\nThanks,\r\n";
echo nl2br($mystring);
?>
OUTPUT:
converts \r \n to <br />
try this:
echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
I know this is an old post but if like me you are have stumbled across this issue and the above didn't work for you, this solution may help you instead:
echo nl2br(stripslashes($row["comments"]));
or (they are not the same function, note the additional "c" after strip)
echo nl2br(stripcslashes($row["comments"]));
See original thread that helped me: nl2br() not working when displaying SQL results
Most likely you are doing escaping twice, when adding your data into DB.
Check your code that adds data to DB and remove unnecessary escaping.
Most likely it's some senseless "universal sanitization" function.
Well it's easy.
Let's take a quote, not a newline to demonstrate. The behavior the same.
Slashes being stripped then data goes to database.
Thus, in the normal case:
source: It's
after escaping: It\'s
by the query execution slash being stripped and
both in the database and back It's
in double escaping case:
source: It's
after escaping: It\'s
after second escaping: It\\\'s
by the query execution slash being stripped and
both in the database and back It\'s
we have our data spoiled.
Just make yourself understand that escaping i not something magical that makes your data "safe" (and, therefore can be done many times, as you probably think). It's just adding a backslash to certain symbols.
My guess is that the slashes in your DB are literal slashes (followed by n or r), not newlines. Can you find a way to store literal newlines in your database?
Following solution will work for both windows as well as for linux/unix machine
str_replace(array("\\r\\n", "\\r", "\\n"), "<br />", "string");
Make sure that you are not to using strings from file and/or set in single apostrophe. Because string is treated literally, and nl2br will not work.
NL2BR will work with double apostrophe.
Building on what Christian is saying, why don't you trying replacing the literal '\r\n' with "\r\n"?
Data you have stored is allready added the slashes.
You have to use stripslashes() first then str_replace()
stripslashes(str_replace('\r\n','<br/>',$row["comments"]))
For some reason this didn't work for me...
echo nl2br(stripcslashes($row["comments"]));
But this did...
$comments = stripcslashes($row["comments"]);
$commentsWithBreaks = nl2br($comments);
echo $commentsWithBreaks;
Not working for me either. I just did the following:
$mensaje = str_replace("
", "<br/>", $mensaje);
I was able to replace newline with <br> using this code :
str_replace(array("\r\n", "\r", "\n"), "<br>", "input");
(windows machine)
This could be a solution, at least it was for me.
$message = str_replace("\\r\\n", "<br>", $message);
It is possible that you are getting a string in which the slashes are escaped (i.e. \\) and nl2br works with \n\r not \\n\\r
Once you understand this, the solution is easy :)