Making a string safe by removing all javascript codes and events - php

I want to remove all javascript codes from a string that contains html code.
For example these are some unwanted javascript codes that may cause problems on your website:
<div onmouseover='window.location = "http://To-Undesirable-Location"'></div>
or
<img onload='window.location = "http://To-Undesirable-Location"'></img>
or
<script language="javascript> ...unwanted code... </script>
Since hackers can use this js functions to redirect your page to some unwanted pages I wonder why there are not some good source to make this type of content safe... On any website there are usually a simple WYSIWYG editor that users can put their html content inside it.
Thanks

I've heard good things on Stack Overflow about HTML Purifier.

Related

How to print an html file with textarea in it into another textarea without being parsed by the browser?

I want to edit my php or html files on the server without logging in. I wrote a php file to import the file contents that I want to edit. The file contents will be printed in a textarea.
It does work. But, when I import a file with textarea, the browser parses the </textarea> from the file as its end part of the textarea. And the rest parts after will also be parsed, too.
Is there any methods to prevent the browser from parsing the file?
The HTML inside your textarea needs to use HTML Entities instead of the actual symbols. That way it won't be parsed.. so that's something like this:
<html> ... </html> <!-- no entities -->
<html> ... </html> <!-- entities -->
I bet there's a lot of functions that can help you with this, like htmlentities() or some JavaScript equivalent, that link leads to css-tricks where a really simple JS one is. JS doesn't have a native one, afaik.
Your PHP mustn't be executed, but as Progman stated:
When the source code is added to the content of the textarea (with
functions like file_get_contents()), it is not parsed by the PHP
interpreter. So it is not required to switch to a .html file to
prevent any PHP executions (there is none).
So, that solves this issue.

Show Editor Content in HTML page

I am using Editor to change the Code Design, But when I retrieve the Code using PHP, it disturbing the Complete page Design.
<p><?php echo substr($postData['short_description'],0,POST_DESCRIPTION_LENGTH); ?>....Read More.</p>
How can i resolve this.?
It could be that the data your are getting through the $postData variable has html elements in it. You should wrap it with the method htmlspecialchars() to sanitize it. This will also protect you from possible XXS-attacks.

Simulate PHP Include Without PHP

I want to include the same navigation menu on multiple pages, however I do not have PHP support, nor can I affect my server in any other way.
I want to avoid simply copying and pasting the html onto all the pages as this would make updating the menu a pain.
The two options I can think of are as follows:
1) Have all the content exist on one page, then determine which content to show based on a keyword appended to the url:
example.com/index?home
example.com/index?news
2) Include a javascript file that has a function that writes the menu out and call the function on each page
function setupMenu() {
$("#nav").html("<ul class='nav'><li>home</li><li>news</li></ul>");
}
With Option 1, the updating process would consist of editing one nav menu on the one page
With Option 2, updating would mean changing the function in the javascript file
My concern with Option 1 is that the page would have to load a lot of content that it wouldn't need to display. My concern for Option 2 may seem trivial but it is that the code can get messy.
Are there any reasons doing it one way would be better than the other? Or is there a third superior option that I'm missing?
You have a few options, each with its own advantages and drawbacks:
Server Side Includes, or SSI. If you don't have PHP there's a good chance you don't have SSI either, and this option requires some irritating mucking-about with your .htaccess file. Check Dominic P.'s answer for a writeup of SSI. The benefit of SSI over JavaScript or Frames is that it doesn't require the user to have JS enabled - which a lot of users don't - and it also doesn't present any navigational difficulties.
Frames. You could either use standard frames to put the navigation in its own separate file, and with the correct styling it would be seamless. You could also use an iframe to place your navigation in an arbitrary part of the site, like a sidebar or whatever. The downside to frames, particularly standard frames, is that they tend to make bookmarking, links and the forward/back buttons behave oddly. On the upside, frames don't need browser compliance or server support.
JavaScript. You can refer to any of the other answers for excellent explanations of the JS solution, particularly if you're using jQuery. However, if your site isn't otherwise dynamic enough that your users will want to have JavaScript enabled, this will mean that a large number of your viewers will not see the menu at all - bad, definitely.
-
Yes use .load jQuery ajax function
$('#result').load('ajax/menu.html');
That way your code stays clean, and you can just edit the includes in seperate HTML files just like PHP.
You should consider AJAX for this task. Include a third party library like jQuery and load the separate HTML files inside placeholders, targeting them by ID.
E.g, in your main HTML page:
<div id="mymenu"></div>
Also, in your main HTML, but in the HEAD section:
$('#mymenu').load('navigation.html');
But your best bet would be to switch to a hosting that supports PHP or any other server-side includes. This will make your life a lot easier.
Check out Server Side Includes. I don't have a whole lot of experience with them, but from what I recall, they are designed to be a solution to just your problem.
Server-side includes: http://www.freewebmasterhelp.com/tutorials/ssi/
You can use HTML Imports http://w3c.github.io/webcomponents/spec/imports/
Here is an example from http://www.html5rocks.com/en/tutorials/webcomponents/imports/
warnings.html contains
<div class="warning">
<style scoped>
h3 {
color: red;
}
</style>
<h3>Warning!</h3>
<p>This page is under construction</p>
</div>
<div class="outdated">
<h3>Heads up!</h3>
<p>This content may be out of date</p>
</div>
Then index.html could contain
<head>
<link rel="import" href="warnings.html">
</head>
<body>
...
<script>
var link = document.querySelector('link[rel="import"]');
var content = link.import;
// Grab DOM from warning.html's document.
var el = content.querySelector('.warning');
document.body.appendChild(el.cloneNode(true));
</script>
</body>

Filtering user input as CSS

I'm providing a way for my users to change the CSS of their user pages by entering some CSS in their settings page. Here is the HTML:
<textarea class="code" name="Settings[css]"></textarea>
In the controller:
$model = new Profile;
$model->css = $_POST['Settings']['css'];
I currently don't validate the input for the CSS field. I was wondering if I could filter the CSS so that they couldn't put harmful code in to the page. For example, they could do:
</style>
Now I can put bad code in to your page
I don't think purifying css with HTMLpurifier would be appropriate because CSS usually contains special characters, but correct me if I'm wrong.
Thanks
This has nothing to do with Yii in any shape of form.
The "invalid code" that you provided in example could be easily removed, if you include the User CSS as an external file.
And that is not all they can do with CSS. You should manually remove following entries:
line containing behavior: url( .. )
all instances where !important is used
entries which contain selectors to specific ID, like #ads and #logo
strip_tags() can remove html tags from the input, though I don't think it's the only thing you have to worry about.
An easier solution may be to load this style through an external stylesheet (<link rel="stylesheet" type="text/css" href="userstyle.php?uid=1235" />) instead of an inline style block, that way there's no way to break out.
You could try a php css parser like this:
https://github.com/sabberworm/PHP-CSS-Parser
But I can't tell you anything about the quality of code it produces or how it handles problems with input.
What I do know is that LESS has good debugging usually.
If you use the LESS php class you could build a system where the $_POST['Settings']['css'] is used to create valid CSS. Or if errors occur you can catch them and return that to the browser.
Yes this effectively enables you to use LESS syntax in the field but I don't see the harm in that. LESS is in some ways stricter in the syntax of CSS through, requiring semicolons regardless of if its the last property in the list and extra characters can also trigger errors.
The debugging information for the javascript version is pretty solid though, I can't personally vouch for the PHP class since I only use the JS, but from what I hear its the second best thing after the JS.
http://leafo.net/lessphp/
http://lesscss.org/

Can I source a php file as javascript?

I am using a WP template that allows me to incorporate arbitrary HTML. Unfortunately, I have to use this particular widget and can't use other WP widgets.
I have on my webserver /some/path/serve_image.php that spits out a random HREF'd IMG SRC with a caption and some other info from a MySQL query.
Now...how can I say "take that output and treat it as HTML"? If I just put "/some/path/serve_image.php" I get that literal string.
I tried:
<script type="javascript" src="/some/path/serve_image.php"></script>
but that didn't work. I tried changing everything in serve_image.php to be document.write() calls and that didn't seem to work either. I'm not the world's greatest JS guy...
So if I have a URL on the net that spits out some HTML and I want to include that HTML in my web page, what's the best way to do that? Sort of like what Google does with Adsense - you source their show_ads.js.
Why no? Add
header('Content-Type: application/javascript');
And output JavaScript Like:
echo("var image = \"".$images[array_rand($images)]."\";");
echo("$('img.randim').attr('src', image);
No. JavaScript and PHP are two completely separate languages. In fact, if it was JavaScript, you aren't even loading it the right way.
<script type="text/javascript"></script>
The way you're trying to do it would throw a parse error, because it would try to use the PHP as JavaScript. Some browsers would even reject it, because PHP files have a text/html MIME type, while JavaScript should be application/javascript.
PHP has to be done server side, so loading it in the client just doesn't work.
What I think you're after is this:
<?php
require('/some/path/serve_image.php');
?>
Just place that wherever you want the image to be.

Categories