I am trying to display code on a webpage, just as text, for the user to view. The code snippet is obtained from a database, input using a form, and put in a div using PHP. Jquery is then used to replicate the html of that div in another element. The code from the database will never be executed; I am basically just making notes.
Code example: alert('Hello'); (could be PHP or html)
What is the best way of displaying this as text, in my browser?
Filter it somehow using PHP as it is input using a form.
Use of HTML tags (pre, xmp tags, CDDATA).
Convert special characters with some javascript function.
combination of the above.
Example of use below.
PHP
$inputQuery="SELECT x FROM y";
$input = mysqli_query($dbc,$inputQuery);
$row = mysqli_fetch_array($input);
//no issues above, just used to clarify the issue. If $input is javascript code, the below doesn't work.
echo'
<div id="inputCode">'.$row["x"].'</div>';
JAVASCRIPT/JQUERY
var inputCode = $("#inputCode").html();
$( "#displayInputCode").html(inputCode);
Use htmlentities() to convert all the HTML special characters to entities, so they won't be executed:
echo'
<div id="inputCode">'.htmlentities($row["x"]).'</div>';
For HTML you can use htmlentities() which would protect against malicious data like <script> tags that include bad stuff; and for PHP you're already fine since echo'ing PHP code does not execute it (and browsers doesn't execute PHP code either).
Example code :
echo '<div id="inputCode">'.htmlentities($row["x"]).'</div>';
Related
I am trying to create a preview HTML division wherein I face a challenge.
When I try to get code from the textarea and print it in the HTML, I could not see the PHP code. Here's are my codes,
HTML Where the code from textarea will be printed
<pre id='pques'></pre>
jQuery code that will take value from textarea and put in the above HTML pretty print area:
jQuery(document).ready(function($) {
setInterval(function(){
$("#pques").html($("#eques").val());
}
});
Value inside the textarea with id=eques
What will be the output of the following php code?
<div class="code"><?php $num = 1; $num1 = 2; print $num . "+". $num1 ; ?> </div>
Someone kindly help me to achieve this. I want somewhat similar functionality to the stack overflow question preview stuff.
Thank you.
The simplest way to do this is to escape the angle brackets in the PHP open and closing tags as HTML entities:
<?php .. ?> becomes <?php ... ?> - PHP will not treat this as server code and will ignore it, but the browser will display < as < and > as >. This way you don't need JavaScript to do it, you can print it directly to the page. I would advise always HTML encoding any PHP code that is input on your site, and storing it with entities rather than executable code.
As you use jquery, you can achieve this as described here
This will escape the brackets as #kallum-tanton already pointed out.
I've run into a bit of a design problem. I have a webpage with a button. The page is written in php. The php outputs HTML that uses jQuery to initialize a button. When I click that button, a jquery dialog appears. The contents of the dialog are created from an object in PHP. and passed from a php object, but require formatting in Javascript, which is also passed from the php object.
A simplified version of the code would look like this:
$obj = new Custom_Object();
echo <<<EOD
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>" + {$obj->print()} + "</div>");
dialog.dialog();});
</script>
EOD;
with $obj->print() looking something like:
$return = "<p>Some HTML</p>";
$return .= "<script>Some Javascript to format the 'Some HTML' paragraph</script>";
return str_replace(array("\r", "\n"), '', $return);
My questions: (1) Is there some obviously better way of writing this code that just isn't occurring to me; and (2) how does the browser deal with the fact that there are two sets of \script\ tags nested inside of each other? (For some reason the code doesn't work and I am guessing that this is what is causing it, but I am not sure).
Answer to question 1:
You could just write your normal HTML and then insert the PHP values inside of it, without using a heredoc, like so:
<?php $obj = new Custom_Object(); ?>
<input type="button" id="button1">
<script>
$("#button1")
.button()
.click(function(){
var dialog = $("<div>"+<?php {$obj->print()} ?>+"</div>");
dialog.dialog();
});
</script>
Answer to question 2:
The second script tag is not being nested inside of the first, it just seems like it. The second script tag is actually being inserted in a completely different place in the DOM by jQuery after your code is interpreted.
If you think it may be getting interpreted incorrectly, you should try wrapping your JavaScript in CDATA tags and escaping quotes properly inside of the string generated by PHP.
You can achieve a lot more stability by simply "closing" your php tag and re-opening it later in the document.
So for instance, you could have:
<?php
$obj = new Object();
?>
<input type="button" id="button1">
<script>
$("#button1").button().click(function(){
var dialog = $("<div><?php $obj->print(); ?></div>");
dialog.dialog();
});
</script>
Just remember that what ever you output from $obj->print(); will need to have double-quotation marks escaped
Most modern browsers are able to work very well with more than 1 tag.
I'd also advise that you set the script type by changing your opening tag to .
I am trying to append new row to my table, but some input fields got some value retrived from mysql. I know that php is executed server side and javascript client side. Help me with this.
Code that needs to be appended :
<td>
<select name="categories[]">
<?php foreach(categories() as $row){
foreach($row as $key=>$cell){
echo '<option>'.$cell.'</option>';
}
}?>
</select>
</td>
So my jquery append is the exact code above turned into a string:
SOMECODE.append('<td><select name="categories[]"><?php foreach(categories() as $row){foreach($row as $key=>$cell){echo "<option>".$cell."</option>";}}?></select></td>');
So how can i append my php code by using jquery ?
You can mix PHP with JavaScript, assuming that it is running on a valid PHP page.
For example, the following should achieve what you're trying to do:
var td = SOMECODE.append('<td />'),
sel = td.append('<select name="categorii[]" />');
<?php
foreach(categorii() as $row)
{
foreach($row as $key => $cell)
{
echo "sel.append('<option>$cell</option>')";
}
}
?>
Yes you can, but it won't execute. You said it yourself. It's a server side language. What you need is ajax. Just make a php script that echoes the data you want. Receive them client side and append the data.
You cannot, and there's no need to. Instead, you would use Ajax to grab the new information and then JavaScript to create elements to hold that data and append that information to the DOM:
So the question is not how to execute the PHP code by javascript, your problem is how to get the right Data into Javascript.
There are different possibilities:
You could reload your page and appand a parameter to your php-skript allowing it to select the right data
you could request the data using AJAX. You will need to create a skript that take, as per previous point, parameters from the AJAX Call and deliver the right data in the result. Javascript will do the rest
Since your example doesn't need any information for creating the cetegories, you just need a php script creating them. There is no need to deliver a page and asking javascript to get Data, which is static. Just deliver this static data with your page.
You can't append php code using javascript. PHP is run by the server and javascript is run on the browser. However in a PHP file you can use a <script> tag to create a function to do this.
<script>
function appendCategories(SOMECODE) {
SOMECODE.append('<td><select name="categorii[]"><?php foreach(categorii() as $row){foreach($row as $key=>$cell){echo "<option>".stripslashes($cell)."</option>";}}?></select></td>');
}
</script>
I am trying to parse a webpage and print out a table which is on the webpage. I am using php_simple_html dom parser. However, when I try to parse the table off the webpage, all the javascript commands to output the table get turned into comments within the php:
<html>
<script type="text/javascript" src="jquery.js"></script>
<?php
include 'crawling/simple_html_dom.php';
$html = file_get_html('http://uiucfreefood.com/');
$ret = $html->find('body', 0)->find('div', 10)->find('table',0); //gets to the table tag
echo $ret; // nothing is echoed out because the original webpage uses jscript commands to write the table to the page but these commands get turned to comments for some reason.
?>
</html>
When I inspect the element of the page where I am echoing the parsed information I am able to see that the table tag with all the info is in there but the jscript commands have been turned into comments. Is there a way for me to just grab the info and echo it out myself? I tried adding another ->find('tbody'); at the end of the parse command but it doesn't do anything. Any advice is appreciated. Thanks.
EDIT: You can try this code out yourself if you download the simple_html_dom.php and include it in your php file. Source: http://sourceforge.net/projects/simplehtmldom/files/
EDIT: Just noticed something really important. The javascript commands are commented out in the original webpage also. Instead, the original webpage is using a javascript function to print out the table which I do not have defined. Writing that function myself should fix the issue.
EDIT: yup, that worked.
Try using file_get_content instead of get HTML and see if that works. Honestly, depending on your needs, you should code your own parser. It is not that hard to write a parser for the table scan and display.
You will just need the following;
$array = split("<table>", $content);
$boolPlaceHolder = false;
and you can then set the placeholder to true when you encounter this way you can scan through the chars of the content and grab the table.
Hope this helps.
I use the following PHP code to generate some JS and echo it in my page
$var_x = $var_x . "var_array[$var_count] = '<div class=\"var_div\"></div>'; ";
However, when I try to validate it with the W3C validator, I get the following error.
'document type does not allow element "div" here'
The error highlights the > at the end of the tag
What could be the problem?
Use the XHTML CDATA section to denote areas where you may be working with HTML. This will let the validator know that it needs to ignore the contents and not try to parse it.
Yes, this will error out, because you are trying to build html document element inside javascript.
If you echo php variable $var_x in the javascript, it will write your string into document and your string contains document element and when HTML try to parse your html and javascript it will error out.