Do I need to escaping html output in input field? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In my database I have data for example a code such as this: <script type="text/javascript">alert('Xss done');</script>
I get the data from database and I need to populate them in input field. My user then can edit the code. I confuse whether I need to escape the javascript code in my input field because I understand you only need to escape it if you display it with <label>, or <p> element etc etc.
But right now I'm getting alert box with that code. Should I escape it?? If yes then how can I properly escape it because I use this code htmlspecialchars($user_input, ENT_QUOTES) and the javascript code in the input field successfully turn into this <script type="text/javascript">alert('Xss done');</script> but I'm still getting the alert box??
Please help me and thank you.

Do I need to escaping html output in input field?
Yes, every input must be escaped. Especially if it comes from the user. You should never ever trust user's input.
htmlspecialchars has some sort of a bug where you can't directly include strings in it's second and third parameter. Therefore a workaround is needed.
As of PHP 5.4+ the default charset is UTF-8 before that it was ISO-8859-1
ENT_IGNORE Will just drop all invalid code. This is bad for two reasons: First, you won’t notice invalid encoding, because it will be simply dropped. Second, this imposes a certain security risk
ENT_SUBSTITUTE Is a new alternative option which has more sensible approach at the problem: Instead of just dropping the code units they will be replaced by a Unicode character (U+FFFD). So invalid code unit sequences will be replaced by � characters.
/**
* htmlspecialchars fix|hack. Well done PHP, well done...
*/
define('CHARSET', 'UTF-8');
define('REPLACE_FLAGS', ENT_QUOTES | ENT_SUBSTITUTE);
function filter($string = null)
{
return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
}
For more information how to prevent XSS, SQL injection see these links:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?

Your right about using htmlspecialchars(). Here is an example which works:
<input type="text" value="<?php
echo htmlspecialchars('<script type="text/javascript">alert("Xss done");/script>')
?>"/>
which produces
<input type="text" value="<script type="text/javascript">alert("Xss done");</script>"/>
This will display an <input> field with the text as is (including <scripts> tags) and not trigger any alerts. The default flags ENT_COMPAT | ENT_HTML401 for htmlspecialchars() should be ok.

Related

Preventing user from typing multiple characters in the input with JS/jQuery [duplicate]

This question already has answers here:
Limit number of characters allowed in form input text field
(14 answers)
Closed 4 years ago.
I'm trying to write a function, that prevents user, from typing more than one character in the input. Basically, every time user hits any key, the function checks, input value's length, and if it's greater than 1, it sets input value to the first character of typed word. Will this code work out, and if not, how should it look like? (as I mentioned in title, I'm also using jQuery):
function keepOneLetter(){
$("input[type='text']").keypress(function(event){
if($("input[type='text']").val().length > 1){
$(input[type='text']).val() = $(input[type='text']).val($(this).val()[0])
}
}) }
Update
This has been proposed as a duplicate of this one. Well, it could be like that, because:
When I typed title to search bar (preventing user from typing multiple characters in the input with JS/jQuery), no results popped up, because I mentioned JavaScript and jQuery, while the first question didn't to it at all.
Speaking of JS/jQuery, if you compare tags, you'll notice, that I used javascript and jquery tags, while the other question had html, forms, input, textbox, so if you were looking for post about, let's say javascript, you wouldn't find original post.
Eventually, I stuck to HTML solution, as it didn't require JS at all, and it was much faster than writing whole function myself. Well, there was an answer, in which someone wrote function as I initially wanted, and it worked too, but probably due to choosing html solution, Stack Overflow thought, that I've just looked at previously mentioned question, as the best solution considered by author of mentioned above question, was very similar to best solution of my problem.
Using HTML is optional, it's up to you, whether you stick to pure JavaScript, libraries like jQuery or just HTML. As I said, I used HTML, because it was faster. But I could also use function.
What about maxlength?
<input type="text" name="letter" maxlength="1">
This is not javascript, but it works better with less code.
Try this code:
$('.onealphaonly').bind('keyup', function() {
const node = $(this);
node.val(node.val().replace(/^([a-zA-Z]).*/g, '$1'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="onealphaonly"/>

How to pass html content of a div as form parameter to the server

What is the best way to pass HTML data to server.
I have a htmlPage which has a div.I want to pass the innerHTML of this div to the server so that I can save it in session and recreate that div later during the edit flow.
I have created a hidden field:
<input type="hidden" name="selectedTemplateHtml" id="selectedTemplateHtml" />
In this hidden field I want to set the HTML of that div and post to server.
Please suggest.
I tried simple passing the html from div using $("#divName").html() but when in edit flow we retrieve the stored value it gives exception since it is not able to store the html in the javascript variable as the HTML spans many lines.
Please suggest.
In my case I am able to post the request with newlines and I am able to get back the html which I had posted but when I try to store it back in a javascript variable due to new line characters and double quotes it gives error
#Alexander
Following code is used to display html in edit flow:
cdHtml="${postAdBean.cdHtml}";
templateId="${postAdBean.templateId}";
$("#"+templateId).html(cdHtml);
It gives exception in browser console on the first line ie.:
cdHtml="${postAdBean.cdHtml}";
This is because it is not able to convert the html returned from server to a javascript string.
Okay I got it to work thus:
From client before setting the html in hidden field I encode it :
selectedTemplateHtml=encodeURIComponent(selectedTemplateHtml);
$("#selectedTemplateHtml").val(selectedTemplateHtml);
This is neccessary to escape certain characters like & in the HTML which may otherwise cause issues.
In java:
String
cdHtml=URLDecoder.decode((request.getParameter("selectedTemplateHtml")),"UTF-8");
cdHtml=cdHtml.replace("\n"," ").replace("\r", " ").replace("\t", " ");
cdHtml=cdHtml.replace("\"", "\\\"");
ie. first i decode the html then replace all the newline characters and escape the double codes. Then i send the html back to browser and it is readily assignable as in javascript without any issues.

Html : how to get value of input from form? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have got the following code:
<form method='POST' onsubmit='javascript:searchAndUpdateGrid(GET_THE_VALUE_OF_INPUT);return false;'
<input type="text" id="inputField" class="form-control" placeholder="Type something...">
</form>
I want to launch the function searchAndUpdateGrid with the value entered by the user in the input field. How can I do that ? (I would like to avoid to get it from Javascript)
Thanks !
Take it easy. You must write some javascript code for onkeyup event to doing that.
$(document).on('keyup','#inputField',function(){
searchAndUpdateGrid();
});
function searchAndUpdateGrid(){
var inputtxt = $('#inputField').val();
$.post('file.php',{text:inputtxt},function(data){
//type statement for after success the server request.
//Example you must put the result of destination file in to the
//HTML div that we assume it's id 'preview' then
//you should be type that code
$('#preview').append(data);
});
}
It will working fine.....
This is Jquery AJAX post method. But you can use GET method. If you using get method then you should change $.post to $.get. Another problum is what is inside the curly brackets?This is the parameter of you hoping to send textbox values to destination php or asp file.It might send your textbox values as text parameter.
$("#inputField").val() would give you the value of the input (with the help of jQuery). You are using javascript and looking for a javascript function - so there is no way to not get it from javascript. alternatively you can use PHP and get the value from the file that gets the form (the one specified in the 'action' attribute) with $_POST['inputName']

Input text from html to javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I don't understand how to make and use forms. Can someone give me and example using external java script where there is an input text and a submit button and when it gets click it does a java script function. I also have some questions. If i'm not using a form to change pages do i need a method. What do i put for the action attribute. Are forms the best way to get input text data to java script. And why should i use a form and not just input tags.
Thanks.
No, you don't need a form to collect user input form fields.
Here is a really simple friendly example using MagJS:
HTML:
<div id="hello">
<label>Name:</label>
<input name="hello" placeholder="Enter a name here" />
<hr/>
<h1>Hello <name/></h1>
</div>
JS:
mag.module("hello", {
view: function(state) {
state.input = {
_oninput: function() {
state.name = this.value
}
}
}
})
Here is a link to the working example: http://jsbin.com/fivaqoliqe/1/edit?html,js,output
Hope that helps!
The short of it is that W3Schools lets you play around but they are scarce on explanation so I suggest you check out this resource instead (which also has a demo of a form): https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
The action attribute is where it should go after it is done to further process the form (typically a route or backend server is where you will go after). Given what you have been talking about however, you only have one field and one button, so you should look into the onclick attribute and then look up the input field and read the value. You use a form when you have a lot of inputs that are related and should be sent at once. There's a lot out there though as this is very basic but if you have any questions just ask.

How to allow only Hebrew letters in input for mobile page, and few more questions? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am little bit new to html and php programming so I wondered if there is a way to do the following things :
I have this input html code that should get a full name of a person.
<form action="createName.php" method="post">
<input dir="rtl" name="fullname" type="text" placeholder="שם פרטי + שם משפחה" />
<button style="width: 100%;" class="button block green" type="submit" id="login"> המשך לאפליקצייה</button>
</form>
This code supposed to be only for mobile devices, and I want to know if there is away to allow only Hebrew letters in this code ? I tried few things that didn't work maybe because its on mobile I am not sure, anyone have Ideas ?
Strange thing happens then A person start the typing inside the input, then the mobile keyboard shows up the input stays in the same position instead of going above the keyboard, The keyboard literally is above the input and the person can not see what he is typing inside, anyway to change it ?
The last question is less impotent because it does work but I would like to get your advice for the way it works, the thing is like this:
There is log in using Facebook application to the website but the data given by Facebook is not enough for me and for this I wrote the code that I mentioned before because I need to have the full name of the person and in Facebook this name is not 100% correct because users usually add nicknames and stuff into their Facebook name. My code working like this, First person logs in with facebook account he is redirected back to main page, why the main page ? because there is a possibility that the user is not a new user and he entered his full name in his first log in, so in the main page the php script checking if this user have entered his full name and if not the script redirecting him to the input page there he is filling his full name. So what do you thing about the way it works ? Maybe there is a way to do is smarter ?
Thanks ahead :)
Use regular expressions in order to filter out any non Hebrew character.
<?php
function leaveOnlyHebrew($str)
{
$strippedStr = trim($str);
return trim(preg_replace('#[^א-ת ]#i', '', $strippedStr));
}
var_dump(leaveOnlyHebrew("azאב azטו"));//only hebrew and spaces
var_dump(leaveOnlyHebrew("azxc gfh"));//empty
?>

Categories