How to utilize htmlspecialchars within echo - php

You can visit this link for an example of my promlem : http://jflaugher.mystudentsite.net/cmweb241/cmweb241_lab2.html
Everything is working correctly, except that I am having problems utilizing the htmlspecialchars in my echo. I am wanting the entity to show up in the echo and not the html character. I have tried placing the htmlspecialchars within the echo, but then the paragraph tags shows up. How do I utilize the htmlspecialchar in the echo, and display the echo in a paragraph tag? I have been at this for some time and have gotten no where, as I am very new to PHP.
For example, when I enter a '&', I get that echoed back. Instead of the '&', I want the entity &amp to be echoed.
<?php
$username = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['username']));
$password = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['password']));
$comment = htmlspecialchars(str_replace(array("'", "\""), "", $_POST['comment']));
echo "<p> Your Username is: $username .</p> ";
echo " <p>Your Password is: $password . </p>";
echo " <p>Your Comment was: $comment . </p>";
?>

Say you enter &.
htmlspecialchars will turn this into &.
& is the HTML entity for &, so viewing the result in a browser displays &.
This is the normal purpose of htmlspecialchars, it preserves the visible character by escaping it for the medium (HTML) appropriately.
If you want & to turn into a visible &, the browser will need to receive &amp;. Apply htmlspecialchars twice to do that:
htmlspecialchars(htmlspecialchars($_POST['username']))
Maybe The Great Escapism (Or: What You Need To Know To Work With Text Within Text) helps you to understand the topic better.

I'm not sure what this means:
I am wanting the entity to show up in the echo and not the html character.
Are you saying that you want the entity to be displayed in your web page? htmlspecialchars is converting the characters to entities, but a browser will display those entities as the characters they represent.
If you want to actually see the entities in your browser, you can double-escape the values:
$username = htmlspecialchars(htmlspecialchars(str_replace(array("'", "\""), "",
$_POST['username'])));
But I don't really think that's the purpose of the exercise you're doing.

If you want to display the entities, you could apply htmlspecialchars() twice and it will turn all the & in & to &amp; and thus the entity itself will be displayed.
Another method is wrapping the output in <pre></pre> tags.

Try this approach:
<?php
$string = "<tag>&";
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
print $string;
It will print:
<tag>&
How to prevent XSS with HTML/PHP?

Related

How to properly or securely output data but still be able to display breaks and special characters inputed

The function below is the one I use to output data
function escape($string){
return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
It works if just need to get strings saved to my database and be echoed
How can I allow certain tags like bold and breaks and still be secured from xss attacks
Here is a sample string I need to work
$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';
Output should just be
HelloWorld
I came up with a solution to my question by combining answers I found on this website.
Here's the code
$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';
// remove script tag along with everything in it
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string);
// remove all tags except the ones you want to work
$string = strip_tags($string, '<br><b>');
// remove all attributes of the html tags
$string = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $string);
echo $string;
For now, it works against the sample string provided.
If you guys know any problem that might occur by using this code please feel free to comment and advice on better way output data securely but still keep certain tags. Thanks!

PHP: getting "SSA's" instead of "SSA's"

Im having a problem displaying certain data with PHP from the database.
How its currently showing - "SSA's"
How it should show "SSA's"
HTML Meta Tag
meta charset="UTF-8">
PHP Code
$article_title = html_entity_decode(mb_convert_encoding(stripslashes($r->ArticleTitle), "HTML-ENTITIES", 'UTF-8'));
You can decode by using these two methods html_entity_decode() or htmlspecialchars_decode()
Basic Example:
$string = html_entity_decode("SSA's");
echo $string; // result SSA's
$string = htmlspecialchars_decode("SSA's");
echo $string; // result SSA's
Remove the html_entity_decode function, as you are double encoding HTML-ENTITIES
And as #ChrisBanks pointed out, you also don't need stripslashes
You need to call html_entity_decode again because the data is being stored as double encoded and remove the stripslashes.
$article_title = html_entity_decode(html_entity_decode(mb_convert_encoding($r->ArticleTitle, "HTML-ENTITIES", 'UTF-8')));
You might want to investigate how the data is being stored in the database as double-encoded in the first place. Perhaps htmlentities is being called twice somewhere.
To add on to the comment:
You shouldn't store data HTML encoded unless for some reason you really and truly need to (there might be some cases you're required to). It is only on output and rendering on a webpage do you want to use htmlentities.

PHP MySQLi escape quotes

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;

PHP getting special characters from database

I have an issue with the special characters. For ex. In the database is written "A & A" (database is set on utf8-unicode-ci).
I am retrieving in autosugest list the values correctly with:
while ($row = mysql_fetch_array($result)) {
$keywords = htmlspecialchars($row['name']);
echo "<keywords>". $keywords ."</keywords>";
}
When I click to select the "A & A" in the input field is filled as A & amp; A
the header is set on :<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Can you please let me know how to display the special character?
If you want to convert from A & A to A&A, use htmlspecialchars_decode on the text.
If you want to convert from A&A to A & A use htmlspecialchars.
In your case removing htmlspecialchars operation on the text pulled from your database will do.
Since your issue appears to be with the & character being replaced with &, maybe running something like $text = str_replace("&", "&", htmlspecialchars($text)); will work better for you, and prevents XSS.
If you have "A & A" in the database, htmlspecialchars will do that.
Remove htmlspecialchars.
Its better use rawurlencode before you inserting the value to database. Then whenever you fetching the value, use rawurldecode. I think it may solve your problem.
rawurldecode($row['name']);
Check this http://php.net/manual/en/function.rawurlencode.php

html source encode

when I view source on my php page I get " for a quote. But instead, I would like " to be used in the source code. I have no control over manually replacing it so Im wondering if there is a function to do such a thing.
If you have access to the PHP and want to change all html special characters to their rightful variations use:
print htmlspecialchars_decode($string);
You could do this very simply using str_replace.
$string = str_replace('"', '"', $string);
However, as Levi said, why not just leave it this way? It should have no effect on the display.

Categories