I'm asking this because I'm using a trick that works but I think my be problematic in the future.
I generate a html form in php using SimpleXML and DOM to manage the source (a html file with all forms needed). So I got my form and got to fill some properties. Here is an example:
<input type="hidden" name="arquivo_tipos" value="{arquivo_tipos}" />
{arquivos_tipos} is a JSON string, won't work inside double-quotes. However, if I create the source code like this:
<input type="hidden" name="arquivo_tipos" value='{arquivo_tipos}' />
After being processed by php, it will return to double-quotes (I pick the form from a lot as a xml node). So my solution is replacing the property with this kind of script:
html = html.replace('"{arquivo_tipos}"', '\'[{"ext":"jpg","nome":"Imagem JPEG"},{"ext":"jpeg","nome":"Imagem JPEG"},{"ext":"gif","nome":"Bitmap GIF"},{"ext":"png","nome":"Imagem PNG"}]\'');
This is JavaScript, but in php I use the same trick with str_replace.
The point is, this is the final code, so it works, but smells like it will fails in the future if another process take this result. Is there a better way, a right way of doing this?
Use php htmlspecialchars function, it can escape
double-quotes to "
single-quotes to '
http://tw1.php.net/htmlspecialchars
Related
When getting the values from MySql database in Google Spreadsheets using JDBC service and I get the ampersand character as & instead of &. I would like to know how should I make the call so I directly get & as value.
I am using the following connection: "jdbc:mysql://ip:port/server?useUnicode=true&characterEncoding=UTF-8". Also, I am using rs.getString() method to take the data from the query.
Thanks a lot!
I am not sure where you are outputting your data, but this is usually a cause:
In HTML, the ampersand character (“&”) declares the beginning of an
entity reference (a special character). If you want one to appear in
text on a web page you should use the encoded named entity “&”
This seems like a simple rule, but what about urls in HTML, javascript files, javascript in HTML, etc… Here’s a little guide to help clear up that ampersand HTML confusion:
Text in HTML:
<p>Jack & Jill ran up the hill.</p>
A link in HTML (or any HTML attribute value):
tired meme
A link in javascript:
window.location = 'http://google.com/?l=1&q=rick+roll';
If you’re using a web framework that escapes variables for you and you pass in a url as a variable into javascript, then you’ll have to make sure it doesn’t encode the ampersands. In Django, you would write something like this: window.location = '{{ url|escapejs }}';
Also, if this is inline javascript—in an HTML document, not a separate .js file—then you still shouldn’t escape the ampersand, which means the document will not validate as XHTML. Either throw it into a separate .js file or stop worrying so much about validating your code.
Inside an onclick in HTML:
<a href="#" onclick="window.location='?l=1&q=rick+roll';return false">
kablammo!
</a>
This is redundant to the second example, but worth pointing out since it’s javascript inside an attribute of an HTML tag.
Dynamically in Javascript (example using jQuery):
$('#result').text('Jack & Jill'); // .text() escapes the text for you
$('#result').html('Jack & Jill'); // .html() sets the HTML directly
document.getElementById('result').innerHTML = 'Jack & Jill';
Reference information: Click Here
Is it possible to print out the value of a field without being rendered?
In other words, if I have an html like this:
<input value="'" />
And I do:
console.log( $('input').first().val() );
The result will be:
'
While, what I would like is the result to be:
'
is it possible?
Please note this is for debugging proposes only.
The HTML entity is converted to the real character when the HTML is parsed and the DOM is created.
Your JavaScript runs much, much, later than that.
To get the original HTML you would need to make a new HTTP request to fetch the source code of the HTML document, and then write a custom parser (which didn't handle entities) to find the part of the HTML that interested you.
I am writing a php script which generates html with a javascript onkeyup event, as such:
// generate the function text
$fn_text = "checkContentQuizAnswer(\"#".$var_name."\",\"".$equation_solutions_array[0][0]."\",\"{'incorrect_values':[";
for($r=1;$r<count($equation_solutions_array);$r++) {
// THIS ISNT WORKING CORRECTLY, NEED A BETTER WAY TO PASS INCORRECT INFO
$fn_text .= "{'equation':'".$equation_solutions_array[$r][0]."','message':'".$equation_solutions_array[$r][1]."'}";
if(($r+1)<count($equation_solutions_array)) {
$fn_text .= ",";
}
}
$fn_text .= "]}\")";
However this isnt working... the code it generates looks something like this:
onkeyup="checkContentQuizAnswer("#theonlyvariable","27.62*5","{'incorrect_values':[{'equation':'27.62+5','message':'you added 5'},{'equation':'27.62-5','message':'you subtracted 5'}]}")"
however, it hasn't been working... the errors have included complaints about missing }'s, MathJax (an eval() style library) is undefined.
Im sure that it is how I am parsing the onkeyup part of the tag but i cant get the combination/syntax correct.
Can anybody see a glaring problem? :S
Thanks
Alex
Although you are escaping the quotes in the PHP file, the quotes in the javascript parser are not being escaped. Change the quotes inside the onKeyUp to single quotes to fix this. You will also need to escape the quotes in the JSON as well - the json_encode() function can help with that. You need to output something like:
onkeyup="checkContentQuizAnswer('#theonlyvariable','27.62*5','{\'incorrect_values\':[{\'equation\':\'27.62+5\',\'message\':\'you added 5\'},{\'equation\':\'27.62-5\',\'message\':\'you subtracted 5\'}]}')"
I am in need of help again, this time with a little Javascript snippet. There's also a little bit of PHP involved. The PHP is as follows (to generate random numbers)
$no1 = rand(0,9);
$no2 = rand(0,9);
$no3 = $no1+$no2;
I'm using this as a captcha method, for a very simple contact form. I'm not a fan of the bulky methods that I find all over google searches.
To validate this code, I use the following Javascript
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>"){
window.alert("Incorrect security code");
return false;
}
Then inside my form, I just use this:
<?php echo $no1; ?> + <?php echo $no2; ?> = <input name="check" type="text" id="check" size="3">
It all works as it's supposed to, but if there was a way for me to not to just directly echo $no3 in my javascript here:
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>")
Then that would eliminate any way of viewing the source to find the answer. I'm very much aware that it's a simple math problem, and if anyone knows how to view source, they most definitely can add, but a colleague of mine pretty much insisted on this.
So, does anyone know a way to help me out? I pretty much wrote most of this by hand, including the javascript, so please be nice when telling me that my code is horrible and out dated..
Thanks!
Put the $no1 and $no2 variables inside of span tags (or anything else you can directly target with Javascript) and then get the values from those spans with JS and use that to calculate the sum in JS rather than echoing it into the source with PHP, e.g. give the spans IDs like #captcha-1 and #captcha-2 use getElementByID to retrieve the values, then do the validation entirely in Javascript.
It will still be easy for anyone with a brain to figure out how to bypass but at least the answer will not be present anywhere in the source code other than as a JS variable.
If you want to hide the validation process entirely, you will need to use JS and AJAX to send the sum input by the user to a serverside PHP function which checks to see if it is equal to $no1 + $no2 and then submit the form as part of the response success function.
All that being said, this is still a very weak spam deterrent method.
I need to pass a variable to a javascript function,but I got a little trouble.
In the .cs file,I write like this:
string id = "someid";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction("+id+")\">"));
I need to use the value of this id,but in the console.log(id),it just shows "object",not the "someid",what's the problem?
Look at the generated HTML:
<input type="button" onClick="myFunction(someid)">
You are generating a variable name when you want a string literal.
Add some quote marks.
Whenever you have a problem that manifests in the browser: Look at the code the browser is dealing with first. You should always start by determining if the JS you want is not working or if the server side code is not generating the JS you want.
just add '' around id as i did below will resolve your issue
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));
Use the single quotes around id:
'"+id+"' (notice the single quotes then double quotes)
The problem is that it is looking for a saved variable on the page named someid, which is why you are getting the object in the console. Pranay Rana has a good solution which is to make sure the string someid is surrounded by single quotes.