How to sanitize PHP posted in comments by users - javascript

I am creating a commenting system where users can post comments that can also consist of basic HTML including code. Like this:
<pre><code class="language-php"><?php
echo 'Test';
?></code></pre>
The problem is that I can't sanitize this one server side because the PHP code in the comment will actually run on my server. I tried using JavaScript like this before submitting the form:
$("#comment").val() = $("#comment").val().replace("<?", "<?").replace("?>", "?>");
However, this results in Syntax error.
Is there any way for me to safely post user comments that consist of PHP?

to set a new value of input element using jquery, you need to use this syntax
$("#yourElement").val(newValue);
so change your javascript code to:
$("#comment").val($("#comment").val().replace("<?", "<?").replace("?>", "?>"));
read: http://api.jquery.com/val/

Related

Responding to jQuery Ajax request with Python

I am currently trying to implement the pre-built inline editor located here: https://github.com/wbotelhos/inplace
Unfortunately, the support documentation leaves a lot to desire and I have very little experience with Javascript, jQuery, or Ajax.
I have been able to successfully implement the HTML edits:
<td><div class="inplace" data-field-name="name" data-field-value="{{people['name']}}" data-url="/update/{{id}}">{{ people['name'] }}</a></td>
The Js:
<script type="text/javascript">
$('.inplace').inplace();
</script>
and have successfully grabbed, and printed the info sent from the Javascript.
#app.route('/update/<id>', methods=["POST", "PATCH"])
#login_required
def update(id):
new_data = request.get_data(as_text=True)
print(new_data)
return "200"
The issue I am facing, is that the Js returns an Undefined value which is what the HTML updates to.
Ignore the return "200" - I have tired several different methods. Success = True, json values, etc and nothing seems to work.
I am sure I am missing something simple.
It looks like you need to print json with the field name that matches your field_name attribute which is name.
So you will need to print something like this. I don't use python, so you will need to follow actual python syntax. Where the word name is correct, but you will need to add the value that you want shown
print('{"name":"NEW FIELD VALUE"}')

Working with Javascript BBCode Editor

I know question seems different as there are many BBCodes available out there, I am working on client Side BBCode editor and pretty much had done the work.
The issue i am facing is: when i try to parse the server side data with this:
<cfset show = "<script type='text/javascript'>var data = '#JSStringFormat(answer)#';
document.write(PARSER(data));</script>">
in my view source, it shows like this:
<script type='text/javascript'>var data = '[b]Thanks, This ticket has been Updated[/b]. ';
document.write(PARSER(data));</script>
How can i handle this issue?. I need some good suggestions here
use htmlEditFormat in conjunction with your JSStringFormat function.
var data = '#JSStringFormat(htmlEditFormat(answer))#';
JSStringFormat used alone is prone to XSS attacks.
See Nadal's post
http://www.bennadel.com/blog/2570-For-Better-Security-Use-HtmlEditFormat-In-Conjunction-With-JSStringFormat-In-ColdFusion.htm

Stuck trying to display information from JavaScript form

Just working on a class project and I can't figure out what to do next.
I've got a form that is being validated with JavaScript. It's the usual information, name, cc# email, etc.
Well the only tuts I can find relate to how to get the form to validate in the first place, which I've already accomplished.
Now all I need to do is figure out how to get the information that I've captured to display in the confirmation page. I don't need any server side validation if that helps.
Here's a link to the page so far (http://sulley.dm.ucf.edu/~ph652925/dig3716c/assignment4/dinner.html)
Any pointers or references?
<?php
print_r($_REQUEST);
?>
will print whatever value the PHP callback is getting from your form.
=H=
You could try to use the GET parameters to forward the info:
link.to.new.page.html?param=value&param2=value2
etc...
It looks like you're using PHP. If you're sure you don't want any validation, of any kind, then the simplest way to output what was on the form (with some degree of control over what it looks like) is by using the POST global variable in PHP:
<?php
$firstname = $_POST['firstName'];
// etc etc for the other fields
?>
You can then output whatever you want by using those variables. The 'name' property for the HTML fields corresponds to what goes inside the square brackets in the PHP code above.
First, I would like to note that if you are using any server side application, you should absolutely validate the input on the server script before doing anything with it. The client side validation is really intended to make it easier for the user to enter the correct information and can be easily hacked or irrelevant if javascript is off... This said, on the client side, you could intercept the submit event, check the different field values. If you have errors, you display error messages, otherwise, you submit the form. example:
if we have this form:
<form action"myActionscript.php" method="GET" id="#myForm">
// form items here
</form>
and then this script (Beware, code not tested)
<script type="text/javascript">
var f = document.getElementById('myForm');
if (f.addEventListener) { // addEventListener doesn't work in ie prior ie9
f.addEventListener('submit', checkForm);
}else{
f.attachEvent('submit', checkForm);
}
function checkForm() {
// Check all input fields logic,
// you could have an errors array and add an error message for each
// error found. Then you would check the length of the error array,
// submit the form is the length is 0 or not submit the form
// and display errors if the length is > 0.
if (errors.length > 0)
{
// iterate through the array, create final error message
// and display it through an alert or by inserting a new
// DOM element with the error message in it.
// [...]
}else{
f.submit();
}
}
</script>
I have to say that the whole thing would be much easier and certainly more cross-platformed if you used a javascript library like jQuery... ;)

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories