Echoing un-escaped HTML - php

Very unusual question.
I came across some code some years in the pass that was including conditions and normal PHP syntax while echoing all content.
My question is how is that Technic/syntax called. I have been googling with some very broad terms and can't find what im looking for.
If my memory is correct, The code I viewed long time ago had un-escaped HTML and it was not required to start and stop PHP processing with <?php ?>
I Have a method within a class called Template\Labels::User()
the only purpose of that method is to echo the proper html to create a label within my webapp so that the pages are lighten of code and clear to anyone viewing the code.
Id like to avoid, having to <?php ?> for very simple boolean if
Any one know what I am looking for ?
static function User($UserObj,$isLink = true){
?>
<div class="image label bg-purple" style="margin: 4px;">
<?php if($isLink){
?><a href=""><?php
} ?>
<img src="<?php echo $UserObj -> ProfilePicture; ?>" style="height: 2em;" class="img-circle" alt="User Image">
<label style="font-size: 90%"><?php echo $UserObj->FirstName{0}.$UserObj->LastName{0}; ?></label>
<?php if($isLink){
?></a><?php
} ?>
</div>
<?php
}
Edited
After some more research by going through PHP documentation on Operator
I found Nowdoc string quoting
Can someone shed some light onto Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

Its good that you added code to your question so that we can all see what you are dealing with here. Now to me what I understand with your question is that you want to avoid using php tags to echo some html code based on if condition.
<?php
static function User($UserObj,$isLink = true){
$html = '<div class="image label bg-purple" style="margin: 4px;">';
if($isLink) $html .= '<a href="">';
$html .= '<img src="'.#$UserObj->ProfilePicture.'" style="height: 2em;" class="img-circle" alt="User Image">';
$html .= '<label style="font-size: 90%">'.#$UserObj->FirstName[0].#$UserObj->LastName[0].'</label>';
if($isLink) $html .= '</a>';
echo $html;
}
?>
In my thinking I thought you should just have to run php tags once and use a simple variable to add your html code to so that you can print at the end of the function.

I didn't understand some of your images but all the same your issue is printing unescaped html in PHP. In other words you want to have raw html.
There are two functions am thinking of right now which you can use depending on your desired output: html_entity_decode() and htmlentities().
html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.
<?php $orig = "I'll \"walk\" the <b>d
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk&quot
echo $b; // I'll "walk" the <b>
?>
Ref: http://www.php.net/html_entity_decode
I hope this helps solve your issue of unescaped html.

Related

Get the .html after the echo

How to get the link of .html after the .$obj->product_name. ?
I have tried it as bellow. But it only shows the link of http://.com/forbiden insted of http://.com/forbiden rice.html where it cuts the rice.html
echo '<span class="product-name"><a href=products/'.$obj->product_name ."html". 'target=_blank>'.$obj->product_name.'</a></span></br>';
Try with urlencode($obj->product_name)
Hope that helps :)
Attribute values containing spaces must be quoted in HTML (and it is good practise to always quote your attribute values).
The space between forbiden and rice is terminating the attribute value.
URLs aren't allowed to have spaces in them anyway, so you should run the string through urlencode too.
You'll find it easier to deal with the quotes if you break out of PHP mode to output HTML instead of trying to mash it together in strings.
Also note that you should escape text content for HTML with htmlspecialchars as a defence against XSS.
$url = "products/" .urlencode($obj->product_name) . ".html";
?>
<span class="product-name">
<a
href="<?php echo htmlspecialchars($url); ?>"
target="_blank">
<?php echo htmlspecialchars($obj->product_name); ?>
</a>
</span>
<br>

Interpret PHP inside a quote in a PHP

I have this variable $url that I need to print inside a quoted HTML that it's inside a PHP if conditional.
<?php
$url = $thumb['0'];
if ( in_category( 'News' )) {
//nothing here
} else {
echo '<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>';
}
?>
But src="$url;" is interpreted as src="$url;" in the HTML code. It does not interpret as a variable.
How can I solve that?
you can concatenate strings with a dot in php
e.g
echo "This"."is"."a"."sample";
likewise with variables:
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';
When working with strings in PHP, it's important to realize the distinction between single- and double-quoted strings.
Single-quoted strings are basically parsed as literal strings, regardless of what 'special' characters you might use. The only escape sequences are \' for a literal single quote and \\ for a literal backslash. PHP code is treated as simple text, and so are escape sequences like \n (the sequence for a unix newline). This is the format to use for simple string literals like 'Hello World!'.
Double-quoted strings are parsed completely, meaning \n is interpreted as a newline and $var is replaced with the value of the variable $var. So this is much more powerful, but you also have to think more about how your strings will be interpreted. If your interpreted php gets complicated (or is adjacent to non-php that might look like php), you can use braces to clarify your meaning.
Note that there are lots of reasons not to mix strings with php code. Often sprintf, heredoc, or simple concatenation (with .) make things much clearer, as suggested in several other answers.
I like to seperate the business logic from the output. This, in combination with PHP's alternative syntax for control structures, keeps your HTML output clean and easily readable.
See this example:
<?php
// Do some things here
$url = $thumb['0'];
// Below this point we output HTML
// Only use simple control structures here, this keeps your HTML clean and easy to read
?>
<?php if (in_category('News')): ?>
<?php else: ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
Since the first part of the if-statement is empty, you can simplify the code:
<?php if (!in_category('News')): ?>
<div class="image-holder"><img src="<?php echo $url; ?>" alt="Post photo" class="image-border">
</div>
<?php endif; ?>
Use double quotes and surround your variable in curley braces example
echo "This is my variable. It equals {$var}";
you can do like this
echo '<div class="image-holder"><img src="'.$url.'" alt="Post photo" class="image-border"></div>';
or
echo "<div class='image-holder'><img src='$url' alt='Post photo' class='image-border'></div>";
If you need to work with large portions of HTML and don't want to have to change from double to single quotes [technically disallowed by HTML spec], or escape all of the double quotes [pain in the butt], or constantly drop in and out of <?php ?> tags [ugly, hard to maintain], then use a HEREDOC. eg:
echo <<<_end_
<div class="image-holder"><img src="$url;" alt="Post photo" class="image-border"></div>
_end_;
Variables are expanded, no quotes need escaping, and all of your dreams will come true.
Alternatively, you can stick with a single-quoted string and get cozy with printf() which is a fantastically useful function in its own right. eg:
printf('<div class="image-holder"><img src="%s;" alt="Post photo" class="image-border"></div>', $url);
Do this, (EDIT: simplified code)
<?php
$url = $thumb['0'];
if ( ! in_category( 'News' ) ) {?>
<div class="image-holder">
<img src="<?=$url?>" alt="Post photo" class="image-border" />
</div>
<?}?>

using ' and " in php syntax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
Ive started on part of my new year resolution and decided to learn php, as part of it im trying to parse in an xml feed, and echo out the name of the events wrapped in <a> tags linking them back to the events page on the xml feed's site.
I think ive got it all in but i cant seem to see why this isnt working im just getting a blank page, if some one could point me in the right direction it would be much appreciated, cheers
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href="$event_attributes['url']">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
</ul>
echo "<a href="$event_attributes['url']">";
try changing that line to
echo "<a href=\"".$event_attributes['url']."\">";
The Php parser is pretty funny about this. Usually you pick one and just stick to it, or use both single quotes and double quotes as you please. Just remember that strings with double quotes are parsed for variables.
$hello = "Hello";
echo "$hello master";
is the same as
$hello ="Hello";
echo $hello.' master';
When you are testing your PHP scripts, you'll find it useful to switch on errors - then PHP will actually tell you why it isn't showing you anything:
error_reporting(E_ALL);
Normally you will have missed a ; or mis-typed a variable name.
in your case the error is here:
echo "<a href="$event_attributes['url']">";
You have accidentally ended the string with a double quote, so PHP thinks the string ends here:
echo "<a href="
This is where using single-quotes can be very handy because your double quotes won't then close the string.
echo '<a href="' . $event_attributes['url'] . '">';
The main difference between single and double quotes in PHP is that double quotes has special clever parsing rules and single quotes doesn't. For example:
$myVar = "BLAH";
echo "Example $myVar"; // Example BLAH
echo 'Example $myVar'; // Example $myVar
In your unordered list, you should use a dot to concatenate your string, and escape your double quotes like this:
echo "<a href=\"".$event_attributes['url']."\">";
Instead of
echo "<a href="$event_attributes['url']">";
Your example throws and error because you haven't used proper string concatenation. However, even with correct concat, it would render as <a href=http://someurl>, and you'd need to add the double quotes according to html standard. Hence you have to double quote.
if you want to not be troubled by having to switch between using a ' or a " then i suggest using the php alternative syntax php alternative syntax
with the given code it would look like
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php foreach($type->market as $event):?>
<li>
<a href="<?php echo $event_attributes['url']; ?>">
<?php echo $event_attributes['name']; ?>
</a>
</li>
<? endforeach;?>
</ul>
one advantage this would bring is that it would produce cleaner code since you can clearly distiguish your php code from your html which is the presentational part at the price writing all those other <?php ?> and as what others would claim a performance degradation. the choice is yours
Change
echo "<a href="$event_attributes['url']">";
for
echo "<a href=".$event_attributes['url'].">";
You are missing the periods in your second echo, where you have your $event_attributes['url']
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href=".$event_attributes['url'].">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
I would recommend you to enable your error log, it would allow you to know the line with problems in any of your scripts.

Problem escaping php variable

I'm having trouble escaping the PHP variable inside the getItems function:
while($row = mysql_fetch_array( $data ))
{
echo "<div class='favorite'>";
echo "<div style='display: inline;'>".$row['Item']."</div>";
if ($row['UID'] = $uid) {
echo "<div id='unlock'>Info</div>";
} else {
echo "<div id='unlock' onclick='getItems('".$row['Item']."')'>Unlock</div>";
}
echo "</div>";
}
When rendered (is render the word?) anyway, when I see it on my site it says:
onclick="getItems(" whatever')'
What am I doing wrong?
You can see the code here:
http://www.chusmix.com/game/insert/get-items.php?user=19
Your problem is that your attribute values are surrounded by single quotes, but you're also using single quotes in your javascript.
You'll have to use double quotes in your javascript. However, since the whole string (in PHP) is surrounded by double quotes, you'll have to escape them. Hence:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\")' style='display: inline; float: right;'>Unlock</div>";
Or like this:
echo "<div id='unlock' onclick='getItems(\"{$row['Item']}\")' style='display: inline; float: right;'>Unlock</div>";
To clarify what the curly braces do (from the PHP docs):
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }.
To further explain, let's say we have the following scenario:
$name = 'Apple';
$sentence = "$names are my favorite fruit";
What I'm trying to get is: Apples are my favorite fruit. However, this won't work. PHP will instead be looking for a variable called $names, and when it doesn't find it, it'll complain.
So, to remedy this, we can surround our variable in curly braces:
$name = 'Apple';
$sentence = "{$name}s are my favorite fruit";
Great! Now PHP will know where the variable name ends and the string starts.
On a side note: You might consider switching to double-quoting your attributes, since the way you do it now is not valid xHTML (unless you don't care).
Yes, there is a problem with your quotes. It should be this:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\");' style='display: inline; float: right;'>Unlock</div>";
The problem is that your opening quotes for onclick and the quotes around the function arguement have to be a different kind of quote.
This is much easier though to do with html and then just insert the variable like this:
<div id="unlock" onclick="getItems('<?=$row['Item'];?>');" style="display: inline; float: right;">Unlock</div>
Doing things this way instead of echoing HTML when possible will save you tons of time and confusion, and you won't have to worry about all the escaping of quotes
The ' inside onclick is closing the onclick itself. Change it to:
onclick='getItems(\"".$row['Item']."\")'
That way, in JS, it uses a different type of quote.
Even better... you can leave PHP, and have one less type of quote to worry about.
else { ?>
<div id='unlock' onclick='getItems("<?=$row['Item'];?>")' style='display: inline; float: right;'>Unlock</div>
<?php
}
or like so:
echo '<div id="unlock" onclick="getItems('."'".$row['Item']."'".')" style="display: inline; float: right;">Unlock</div>';
If I had to do this, it would have looked like:
<?php while(true) :?>
<div class="favorite">
<div style="display: inline;"><?php echo $row['Item'];?></div>
<?php if ($row['UID'] = $uid):?>
<div id="unlock">Info</div>
<?php else: ?>
<div id="unlock" onclick="getItems('<?php echo $row['Item']; ?>)">Unlock</div>
<?php endif;?>
</div>
<?php endwhile;?>
try the following .
edit: changed to make sure quotes were escaped correctly
echo "<div id='unlock' onclick=\"getItems('{$nameArray[0]}')\" ></div>";

How do I get this while loop to dynamically produce this html?

I am building a picture gallery, that uses this code to display each product I have:
<div class="feature">
<imagetag alt="Image Caption"srcs="">
<div>
<p>
This is some information that can go along with an image.
Anything can be placed here, including images.
</p>
</div>
</div>
I need to create a while loop, that takes all the products in my database, and creates a div of the "feature" class for every instance. I have problems know exactly which symbols need to be escaped and etc. Your help is greatly appreciated.
here is my start:
<?php
($product_set = mysql_fetch_assoc($query)) {
print("<div class="feature"> <imagetage alt="Image Caption" srcs=$product_set[products_image]>"
);}
?>
If you are in a string, every doublequote should be escaped. Because it will close your string.
<?php
($product_set = mysql_fetch_assoc($query))
{
print "<div class=\"feature\"><img alt=\"Image Caption\" src=" . $product_set['products_image'] . ">";
}
?>
Fun thing is, I got a link from someone on stackOverflow about PHP templating. Which was using Smarty. So you don't have to use these print states anymore.
Have you tried:
print(htmlentities($my_html_string))
or htmlspecialchars? htmlentities converts all characters that have one to their HTML escape sequence, while htmlspecialchars converts only those that have meaning in HTML.

Categories