What is the functional difference between these two snippets of code
<!--?php include('json-ld.php'); ?--><script type="application/ld+json">// <![CDATA[
<?php echo json_encode($payload); ?>
// ]]></script>
and
<?php include('json-ld.php'); ?><script type="application/ld+json">
<?php echo json_encode($payload); ?>
</script>
My objective is to apply a JSON-LD file (containing schema.org structured data) to my WordPress site. The first code is taken from this page, and purports to do what I need. But I can't understand why the author would post a snippet with so many comments. From what I understand about HTML and JS comments, the code appears to be functionally equivalent to the bottom code. I am posting here to assure myself that I am not misunderstanding something about this syntax.
Perhaps there is a security purpose for using the commented code? If so, I would be interested in practicing best practices in terms of security.
Thanks.
CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be. This is so that html tags and such can be used without it breaking the xml code - each html tag would be represented as a child-node to the xml. By using the CDATA "comment" you are telling the xml to consider the html tags as a string value, not a child-node.
Regarding the first line: <!--?php include('json-ld.php'); ?--> This isn't including the file - this may be a typo on the original authors' part. If your code works without it, it is probably safe to remove; otherwise, fix it ;)
From what I see, it's purely so that potential output of <?php include('json-ld.php'); ?> are not treated as HTML.
Since most of the time there is no output in <?php include('json-ld.php'); ?> , <!-- <?php include('json-ld.php'); ?> --> just do <!----> . But potential PHP notices or errors that randomly pop will end commented and not breaking the DOM.
Related
I know there are already a few questions like mine but I wasn't able to fix my problem with their solutions.
I got this code in an external html file to include it in others files:
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
The "file" above gets included into this "file":
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
The Variable from the second code should replace the content of the h1 tag in the first code. I know this isn't a forum to get free codes, I just want some inspirations or suggestions. Thanks Guys!
You can replace the html of one element with the html of another element, like so:
$(".replace-me").html($(".variable").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
However, as Rama Schneider pointed out, you might want to get your content in a different way than html.
Also note that this jQuery-solution is done client-side. If you already know the content when serving the initial HTML, you want to do this server-side.
If you have control over the external file, I'd suggest rewriting things so the external file serves a json object of some sort and work with your data from there.
Otherwise it's a simple matter of using JQuery to get the html contents from the variable and use that value to replace the html contents of the 'replace-me'.
You should solve this on server-side if you can. Make the common template a function, like this:
function getHeader($content) { ?>
<div class="header">
<h1 class="replace-me"><?php echo $content; ?></h1>
</div> <?php
}
calculate $content before you call the function and pass it to the function. If you cannot make this a function and you get this as it is from a third-party source, then you can do it via Javascript, like this:
<script type="text/javascript">
document.getElementsByClassName("header")[0].getElementsByClassName("replace-me")[0].innerHTML = "<?php echo $content; ?>";
</script>
Make sure you add this script after the header tag was loaded.
I have a php function as shown below, which takes in an array that has values from an SQL query (in another, not shown function). In this case, the SQL query returns a set of filenames and their associated picture names.
// Take in an array of filters;
// each element is a dictionary of column name
// to the value of that row from SQL query
function displayFilters($filters) {
foreach($filters as $filter){
//output images in img tags, with their appropriate classes
echo " <div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/".$filter['File_Name']."' style='width:100%'>
<div class='w3-container'>
<h4>".$filter['Filter_Name']."</h4>
</div>
</div>
</div>";
}
}
Now, this works fine and will properly display the images as I want. However, I keep having to modify this code, change classes, properties and what not, and if I need to add/modify to the div, I have to go into this function to change everything. Is there a better way to do this than going into the echo function to change it? I'd rather not have to use Javascript if possible, but if that is the only clean way to do it, can someone point me to a way to do this?
<?php function displayFilters($filters) {
foreach($filters as $filter){ ?>
//output images in img tags, with their appropriate classes
<div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/<?=$filter['File_Name']>' style='width:100%'>
<div class='w3-container'>
<h4><?=$filter['Filter_Name']></h4>
</div>
</div>
</div>
<?php
}
} ?>
I do it this way and it seems easy than learning a new template engine
Use a PHP Template Engine
http://www.smarty.net/
Smarty is fast and lean with a small memory footprint.
http://twig.sensiolabs.org/ (Looks remarkably like Dwoo)
Twig is a modern template engine for PHP (Fast, Secure, Flexible)
http://dwoo.org/ (Inspired by Smarty)
Dwoo is a templating system used to make creating websites easier and more structured.
http://platesphp.com/ (Inspired by Twig)
Plates is a native PHP template system that’s fast, easy to use and easy to extend.
http://phptal.org/
PHPTAL is a PHP implementation of ZPT work. To be short, PHPTAL is a XML/XHTML template library for PHP.
I have written how to retrieve query and how to display in below code.
You can use this one. you can also use image tag within table <tr> tag.
$con=mysqli_connect('localhost','username','password','databasename');
$sql="SELECT `COL 1` , `COL 2` , `COL 3` , `COL 4` , `COL 5` , `COL 12` FROM `TABLE` WHERE 1 ORDER BY `COL 3` ;";
$result=mysqli_query($con,$sql);
<table style="width:100%" >
<tr>
<th>Col1</th>
<th>Clo2</th>
<th>Col3</th>
</tr>
<?
while ($row=mysqli_fetch_row($result))
{
echo "<tr><td>".$row[0]."</td><td>".$row[1]."\t".$row[2]."\t".$row[3]."\t".$row[4]."</td><td>".$row[5]."</td></tr>";
}
?>
</table>
I am trying to use a jQuery Plugin for highlighting my Snippet at This Demo but the browser assumes that
<pre class="php">
<?php
echo "My first PHP script!";
?>
</pre>
is a originally PHP code which it is! now the solution is replacing all < with < and > with >
inside the <pre class="php"></pre>
Now can you please let me know how can I use the jQuery to replace all < and > characters inside the with < and > before loading the page?
Thanks
So you got the data with <? tags, it better for you is to replace output of your code serverside with < and > but if you looking for dirty js solution it is would be:
$('.php').each(function() {
var $this=$(this);
$this.text($this.html().replace(/\<\!--\?([\s\S]*?)-->/g,'<?$1>'));
});
http://jsfiddle.net/oceog/x974w2d9/
I not remember if any browser do the replacing of the <? with <!--? but chrome does. The js solution will not work if you have some random examples like: http://jsfiddle.net/oceog/x974w2d9/2/.
Now can you please let me know how can I use the jQuery to replace all < and > characters inside the with < and > before loading the page?
The problem lies in the assumption behind this question. You cannot use jQuery to make this manipulation before the page loads, as jQuery executes after the page loads up in the browser. So your PHP is getting executed and all jQuery will see is:
<pre class="php">
My first PHP script!
</pre>
You need to make sure the string makes it into the output instead of being executed. Something like this should work:
<pre class="php">
<?php
$snippet = <<<EOT
<?php
echo "My first PHP script!";
?>
EOT;
echo $snippet;
?>
</pre>
Someone brought up an argument that having a textarea that accepts too many characters may be risky because people may put script in there.
In my entire existence, I've never heard of that possibility.
Could anyone shed some light as whether or not it is possible to have a script in a text form field and somehow have it executed?
Yes - this is how XSS works. Very simply- you can add script stuff to the dom and execute it that way. For instance, this would fire an alert:
$('#myDiv').html('<script type="text/javascript">alert("hello world");</script>');
Here is a fiddle
Any time you deal with use input, you're at risk of XSS vulnerabilities.
Let's say you have a simple HTML form like this:
<form action="submit.php" method="post">
<textarea name="insecuretext"></textarea>
</form>
And then on your server you have something like this:
<div class="usercontent">
<?php echo $_POST["insecuretext"]; ?>
</div>
For 99% of your users, this will work perfectly, but what if someone submitted this?
<script>somethingEvil();</script>
Your HTML would look like this:
<div class="usercontent">
<script>somethingEvil();</script>
</div>
And then anyone who looks at that page will be affected by the JavaScript.
A really easy solution is to sanitize your input by calling strip_tags()
<div class="usercontent">
<?php echo strip_tags($_POST["insecuretext"]); ?>
</div>
Now, unless your attacker is really clever, you're not vulnerable to XSS in this situation.
Another common situation is if you put insecure content as an attribute of an element. I saw an example of this on a forum a while back where the developers put the contents of the post in a data-content attribute for some reason.
<div class="forum_post" data-content="<?php echo $_POST["insecuretext"]; ?>"></div>
I was able to break this by submitting something like:
foo" onload="somethingEvil();"> <!--
Which printed out as <div class="forum_post" data-content="foo" onload="somethingEvil();"> <!-- ></div>
In this case, all that needed to be done was to convert my special characters to entities:
<div class="forum_post" data-content="<?php echo htmlentities($_POST["insecuretext"]); ?>"></div>
Which would look like this:
<div class="forum_post" data-content="foo" onload="somethingEvil();"> <!-- "></div>
So here's what you should take from this:
Don't trust your users under any circumstances
Never print unsanitized or unvalidated user input
Understand XSS techniques and how to stop them
Know when you could potentially be vulnerable and what you'll do if an attacker gets through your defenses
Understand that length isn't related to security at all. Unless you limit your input to like 3 characters, it could potentially be dangerous.
I've been working on this code for a while. The idea is to get javascript to make a div visible based on the results of a HTML form (not on this page). However, my javascript function never works. I've isolated the problem to the script not being called in the first place. Here's my code:
<!DOCTYPE HTML>
<html>
<body>
<?php
While ($result=mysql_fetch_array($data)){ //I have mySQL code before this
$equipment= $result['safety equipment'];
$equipment2= str_replace(' ', '_', $equipment); //modified equipment name without spaces so that post can read it
$problem = $_POST[$equipment2];
?>
<div style="display:none;" id="<?php echo $equipment?>"> <!--Code that creates a div for each equipment -->
<h1>Report a problem</h1> <br>
You reported that there is a problem with the <?php echo $equipment." in ".$name;?>.<br>
Please describe the problem.
<form>
<textarea row="5" column="300" name="Issue">
</textarea>
</form>
</div>
<?php
if ($problem=="working"){
inspectRoom($UID,$equipment,null);
}else {
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
}
}
?>
<script type="text/javascript">
function Appear(equipment){
alert("hi"); //error trapping
document.getElementById(equipment).style.display='block';
}
</script>
</body>
</html>
$equipment is a string with the name of the equipment (ex: Fume Hood)
$problem is a string retrieved from the previous page. It too has the name of some equipments.
In my console I get the following error:
"SyntaxError: missing ; before statement"
What am I doing wrong?
You're dumping PHP-based text directly into a Javascript context, which is highly dangerous. Any JS metacharacters (especially ') will cause syntax errors and kill the entire JS code block.
echo'var test ='.$equipment.';';
Should be
echo 'var test = ', json_encode($equipment), This will produce syntactically valid JS code, no matter what's in `$equipment`.
Plus, you have MANY other syntax errors. Your php while is NOT contained in a <?php ... ?> code block, so it'll appear directly in your output as raw text. The html inside your while loop is now considered part of the PHP code, so that'll be yet another syntax error. etc... etc... etc.. In other words this code is utterly broken.
Talking solely about javascript since that's what your question is about, your Appear function would never been defined yet since the PHP code would have echoed out the JS that calls Appear before the function is defined.
It is not working because you are forgetting the space after echo. There are other errors also such as your while is not within tags.
For this part of the code
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Replace it with
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo"var test ='$equipment';";
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Th variable isn't surrounded by quotes when the value will be a string;
To start with you are missing a > on line 6.