so i have this block of sql query code here for sending user description to db in node js.
const sqlAddDescription = (desc, id) => {return `UPDATE \`Memcon\`.\`users_list\` SET \`description\` = '${desc}' WHERE (\`id\` = '${id}')`}
it's working completely fine, in the client user inputs a text and the db process goes on with no problem.
BUT if the user sends an input with backticks or quotes or even brackets, the process gonna fail because their text head on goes to ${desc} and it replaces it, so it creates an error.
How can i tell js to fully stringify the text, no matter the inputs.
(i also tried JSON.stringify but that serves a different purpose )
Related
I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.
Imagine your user writes a post and includes a hyperlink or two somewhere within the text. The whole thing is saved as a string in the database. To render the content and make the links clickable, one would do the following:
const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
let content = userInput = "Hey everybody, look at this cool site I found: http://www.cool-site.com"
let url = content.match(urlRegex);
.postContents !{content.replace(url[0], `${url[0]}`)}
The marker !{ } makes sure that Pug treats html tags as what they are. However, this approach is not practical. A malicious user could easily post Click me! and Pug would take this string and render it because the content is being unescaped. If I escape the content, on the other hand, the recursively added tag blahblah will be treated as text and no links will be clickable. One solution I thought about is to decompose the whole string into an array of words to later recompose it again using #{ } for non-urls and !{ } for urls, although it seems rather complicated for a problem many other developers might have encountered already.
Note: I know the code is not looping through all the matched urls. I will figure that out later. My problem now is to find a way to "urlify" the text in a safe way.
You could leverage an existing package like linkify-urls, and pass that through to Pug to be able to use during compilation:
const linkifyUrls = require('linkify-urls');
app.get('/', function(req, res, next) {
res.render('index', { linkifyUrls });
});
.postContents!= linkifyUrls(userInput)
I've tried to develop an UI in JavaScript to parse specific code described in my ANTLR4 grammar. I use a visitor to parse all parts of code and generate a questionnaire. Afterwards, depending on users' input in a JavaScript form, I parse the last part of my code to generate results (it's close to the calculator mechanism drafted into ANTLR book). So far so good. Nonetheless, I would like to modify inputs in the JavaScript form and parse a second time to regenerate and recalculate some results. At this moment, the AST tree becomes empty. I've tried to reinitialise the lexer the parser, the visitor as such as to create a new instance of the parser. It seems that previous parser and lexer are still active and it is impossible to "move the cursor up" to parse again a specific block of my source code.
Thanks for your precious help.
Chris
Below summarised file and script.
grammar.G4
pre
: title ('\n')+
author ('\n')+
;
peri
: (statement ('\n')+)*
(answer ('\n')+)*
;
post
: (feedback ('\n')+)*
;
exercise
: pre peri post
;
//End of Grammar
javascript main class :
class MyExercise {
constructor(){
this.chars = antlr4.CharStreams.fromBuffer(input,'utf-8');
this.lexer = new MyLexer(this.chars);
this.tokens = new antlr4.CommonTokenStream(this.lexer);
this.parser = new MyParser(this.tokens);
this.visitor = new LabeledVisitor(this.exercise,this.parser);
this.parser.buildParseTrees = true;
tree = this.parser.pre();
this.visitor.visitPre(tree);
tree = this.parser.peri();
this.visitor.visitPeri(tree);
this.generateAnswersHTML() // generate HTML results and also inputfields to collect values from user.
this.generateSubmitButton(); // generate submit HTML button
}
generateSubmitButton(){
var button = document.createElement('input');
button.setAttribute('type','submit');
button.setAttribute('value','Check answer');
button.addEventListener("click",this.checkAnswers.bind(this));
document.getElementById("answer").appendChild(button);
}
checkAnswers(object){
var tree = this.parser.post();
this.visitor.visitPost(tree);
this.generateFeeback(); //Generate HTML feedbacks (function of inputed values by user)
}
}
It works well the first time but when I click again on the button checkanswer which calls checkAnswer() method, the tree becomes empty.
There are 2 ways to reparse your input:
Recreate your input stream, token source + parser every time.
Reset your input stream and token source, by
Recreate your input stream or load the new text into your existing one.
Call parser.reset().
Set your input stream again in the token source (to reset it, just calling .reset() won't cut it). lexer.setInputStream(input);
Set your token source in the token stream again, for the same reason. tokens.setTokenSource(lexer);
I'm working with sensor units outfield that spit out data in the form of native text files and have a database created with pre-defined tags. E.G mm, level, voltage. The text file I'm using is pretty unstructured with the data being on the right side of the header separated by semicolon delimiters.
I want to try and import the content into the database where each header matches the tag name and the values are inserted into that tag consecutively. I'm wondering if there's a possible solution or maybe even some tips on how i can achieve this?
Currently i have been working with PHP but haven't gotten to far, is it the best language to use for such a method? Or would javascript be preferred?
Text file is delimited by semicolons:
L;MINVi;Min voltage;V;PTi;Processor temperature;C;AVGVi;Average voltage;V;SDB;Network signal dB;dB;WL02;waterlevel 2m;cm;RSSI;Network signal indication;RSSI;OCi;Operating cycle;sec;SCNT;Satellites;;LAT;Latitude;deg;LON;Longitude;deg
S;170427000428;ERR;SERVER_LOGIN;+CME ERROR: Bad or no response from server
S;170427000428;ERR;FTP
S;170427000450;ALARM_SEND_OK
S;170427000510;WDT;GPS
D;170427000510;SCNT;0*T;LAT;0*T;LON;0*T
S;170427000518;ERR;SERVER_LOGIN;+CME ERROR: Bad or no response from server
S;170427000518;ERR;FTP
S;170427000647;ERR;SERVER_LOGIN;+CME ERROR: Bad or no response from server
S;170502171807;POWER_ON;ML-315;V2.7B1
S;170502171807;SYS_START;BHSDemo 5170991
D;170502171817;MINVi;3.66;PTi;25.8;AVGVi;3.71;WL02;2.86*A;OCi;9.95
S;170502171822;WDT;MODEM_INIT
D;170502171823;SDB;0*T;RSSI;0*T
S;170502171823;WDT;Network signal
database table Tag_data Structure
You can do like this
LOAD DATA INFILE '/yourtext.txt' INTO TABLE TABLENAME;
Your text will be pretty hard to explode every value with it's parameter because every single word end with ; so, first try to make your text file like parameter:value; or parameter=value; or parameter_value; then you can read the content of this file with this php function $content = file_get_contents("path/text_file_name.txt"); now the value of $content variable is equal to the entire text of your file hence, you can split this variable into an array with $splittedcontent = explode(";" , $content); every parameter:value is a parameter in this array like $splittedcontent[0] = parameter0:value0, $splittedcontent[1] = parameter1:value1 and so on, now you can use for loop throw this array and make what your need in you database..
I hope this will help you.
I'm using a textarea to get input from the user and display it on the screen. How can I make sure that if they put in something like
<h1>YAY, I hacked in</h1>
I only display it as it is, and it doesn't display as an <h1>. There must be a function for this. Help? :D
As I commented, if you're about to send that data to a server, you should use one of the various XML Parsers available and strip + validate the input.
If you however, need to purely validate on the client, I suggest you use document.implementation.createHTMLDocument, which creates an fully fledged DOM Object on the stack. You can then operate in there and return your validated data.
Example:
function validate( input ) {
var doc = document.implementation.createHTMLDocument( "validate" );
doc.body.innerHTML = input;
return [].map.call( doc.body.querySelectorAll( '*' ), function( node ) {
return node.textContent;
}).join('') || doc.body.textContent;
}
call it like
validate( "<script>EVIL!</script>" );
You need to address this on the server side. If you filter with JavaScript at form submission time, the user can subvert your filter by creating their own page, using telnet, by disabling JavaScript, using the Chrome/FF/IE console, etc. And if you filter at display time, you haven't mitigated anything, you've only moved the breakin-point around on the page.
In PHP, for instance, if you wish to just dump the raw characters out with none of the user's formatting, you can use:
print htmlentities($user_submitted_data, ENT_NOQUOTES, 'utf-8');
In .NET:
someControl.innerHTML = Server.HtmlEncode(userSubmittedData);
If you're trying to sanitize the content client-side for immediate/preview display, this should be sufficient:
out.innerHTML = user_data.replace(/</g, "<").replace(/>/g, ">");