Can SQL Injection happen other than input Form? - javascript

I use to hear that SQL injection happens when there is input field to make query to database.
I have lots of clickable buttons at CSS menu in index.html , when clicked it performs AJAX:
<script>function bRowse(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","product.php?q="+value,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {document.getElementById("div2").innerHTML = xmlhttp.responseText;}}}</script>
JS will past the 'q' which is VALUE of each buttons to a PHP page to perform sql:
$sql = "SELECT item, price FROM product WHERE item='".$_GET['q']."';
This AJAX works fine. My question is:
1) This is buttons without input field, can SQL injection still happen in this case?
Really appreciate some expert opinions, thanks.

Yes, that can still happen. I could execute your endpoint using curl or a tool like Postman, and send whatever value I want.

Related

How to receive a PHP response in Javascript

I've been stuck on this for the past day and it feels like I am missing something.
My assignment is:
Create a php file register.php which allows users to input their Name, Last name, Username and Email(via an HTML form) and then do some server-side verification on this data.
This file would also serve as an html form where users could input the data.
For the Username input field I have to, on each keystroke, check if a user with that username already exists in my database.
This has to be accomplished using Javascript by sending a request to register.php with Ajax.
I know how to run the necessary query to search my database based on a certain username. That part is not a problem.
What I can't get to work is
using Javascript/Ajax to send a request to register.php
getting register.php to run a query based on the inputed username, since I don't know how to recieve the request
getting register.php to "return" a response without writing it out in the DOM
What I've tried so far:
let username= document.getElementById('username');
username.addEventListener('input', validateUsername);
function validateUsername(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText);
}
};
xhttp.open("POST", "../obrasci/registracija.php", true);
xhttp.send("username="+username.value);
}
this part works and I'm getting the whole HTML document back. I know that because the whole structure is being printed into the console.
now this is the part that I can't get to work. In PHP I've got this so far and I can't get the script to do anything with the username.
if( isset($_POST['username']) ){
json_encode($_POST['username']);
}
Edit: I forgot to add that this site needs to process the data sent with ajax dynamically(if that username is taken, mark the input as not okay until the user chooses a username that's not taken).
That might be a problem in the way I'm using this since the if in PHP only gets tested on first load?
Any help is appreciated.
First, you can check whether or not the request was sent as a POST request (opening register.php in your browser will be a GET request).
You can wrap your form handling by something like this
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check if username exists
if (isset($_POST['username'])) {
echo 'username: ' . $_POST['username'];
die;
} else {
echo 'no username';
die;
}
}
change the code accordingly, use echo json_encode($data) to return your data in JSON format.
In your request, you might need to add the right header to tell PHP how to interpret the body sent with the request.
function validateUsername(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText);
}
};
// add this line
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.open("POST", "../obrasci/registracija.php", true);
xhttp.send("username="+username.value);
}
Also, make sure you have the right naming. In your code example, you refer to your input as the variable username, but you add the event listener to kor_ime, I don't know if you updated something to english and forgot other parts of it for this question or if that is your actual code
let username= document.getElementById('username');
username.addEventListener('input', validateUsername); // here change kor_ime to username and update the function name, you can omit the extra function wrapper

Upload data to the db without stopping the loading of the site

I have a small problem, I created a data analysis system on my site. Everything works, only that every time I run the post to be able to insert the data in the db, it slows down the loading of the site a lot. I was wondering if it was possible to load the data in the database without stopping the execution of the site. For example, if I load and click on an item in the menu I would like it not to let me wait for the data to be entered in the db but to continue with the click I made on the menu item.
My code works this way.
I take the data that interest me with javascript and I post to a php page for data entry
Thank
I don't know if you are using AJAX calls to pass the value from frontend to PHP.
If not, try to use AJAX calls calling the PHP page for data entry and passing the values you want to store. AJAX calls are asynchronous so JavaScript does not have to wait for the server response.
This is an example of AJAX call:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "data_entry.php?value1=exampleOfValueBeingStored1&value2=exampleOfValueBeingStored2", true);
xhttp.send();
}
in the REST paradigm if you need to update values you should use PUT or POST instead of GET. GET should be used only when you want retrieve values already inserted inside database for example.

Which is the correct way to check if a session is still running? Which are some ways?

So I have already had my first experience with Web Design, but there were some things I did in a certain way that I didn't like, mainly because of time. So anyway, I don't know which is the correct way to handle sessions. What I did in my previous project was to embed PHP into HTML and based on whatever was in $_SESSION, usually an id and a user type number, then I'd open or close parts of the website to the user, through embedded PHP.
However, this is not how I wanted to do this initially, at first what I wanted to do was to make a JavaScript code to send a request through AJAX to the server, and check if the session was still active, and based on that open/close parts of the website, but then I'd have to make a request on every page and every so often to make sure the user is logged in. Should I handle something like this client-side?
What are some other ways to check the session but without embedding PHP and using JavaScript instead to modify the HTML document.
To do this, all you need is an ajax request on loop and a php file to check the session.
The Javascript
function checkLogin(un) { //put this function in a loop of some sort depending on how you want to use it
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
logout(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "checklogin.php?un=" + un, true);
xmlhttp.send();
}
function logout(resp) {
if (resp == "false") { //comparing actual text, not boolean
window.location.href = 'logout.php'; //destroy the session or something
}
}
The PHP file checklogin.php (very simple)
<?php
if ($_SESSION[$_GET['un']] != true) {
echo 'false';
}
?>
The php will depend on how you store your sessions, but in this case it is just using one session titled by their username that stores true if signed in. I would recommend making this more complex if you decide to actually use it.

Upload a file through a webpage to mySql database?

I have a HTML webpage with a form to upload a file. When you click submit I want to send the form to a php file where it will store it in my database.
Currently I use the reqular xmlHTTPRequest to send a GET request to my php files. This all works perfectly so I would prefer not to restructure my program.
Could someone give me some guidance as to how to do that? I tried to send the file as I sent other inputs (Text etc) but got a null value in the php.
Code:
The HTML is a simple input tag (this won't show it when I copy it in).
JavaScript:
var picture = document.getElementById("file").value;
generateAjaxRequest("type=insert&picutre="+picture")
AJAX:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange= function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(elementName).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/Controller.php);
xmlhttp.send();
PHP:
$file = #$_GET["file"];
$query = mysqli_prepare($conn, "INSERT INTO table (image) VALUES (?)");
mysqli_stmt_bind_param($query, 's',$file);
stmtGetInfo($query);
When a file is uploaded a user will click submit which will call the Javascript. The javascript sends the file to the ajax which then sends it to the php file. I have only put up some of the code to demonstrate what is happening. All of the methods work for text entry etc.
If you are trying to upload files using xmlHTTPRequest, these links can be usefull.
https://gist.github.com/ebidel/2410898
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Run a PHP function on success of AJAX request completion

I know that in JS, you can use the success of an AJAX function as the trigger to start other events...
So I have just loaded a new page using AJAX. And through this I have also passed some parameters, this is what I have passed:
xmlhttp.open("GET","register-form.php?one="+wordChoiceOne+"&two="+wordChoiceTwo+"&three="+wordChoiceThree,true);
So I now have the variables $one, $two, $three in PHP
I want to complete a couple of tasks using these (concatenate, capitalise, assign etc) before outputting onto the page. However I don't want this to be bound to the click of a button or anything, I want it to be bound to the success of the AJAX load.
How can I now start these actions in PHP?
Pseudo-code:
function setUsername() // RUN ON AJAX SUCCESS{
// capitalise first letter of one two and three
// concatenate together
// Store in variable $username
}
Then ECHO USERNAME OUT
ETA. I have already written the AJAX request and it works fine. Now it's loaded, I want to perform this PHP function, binding the trigger of that function to the success of the AJAX load:
<?php
$_GET['one'], $_GET['two'] and $_GET['three'];
// Capitalise first letter
$one = ucfirst($one);
$two = ucfirst($two);
$three = ucfirst($three);
$username = $one . $two . $three;
?>
EDIT: OK so it appears I can't explain myself, or I haven't understood what is required for this functionality. But here is what I need to happen in plain english, with links.
I am building a registration system. Instead of letting people type in their own username, I have a username builder. You can see this here:
http://marmiteontoast.co.uk/fyp/login-register/register-username-builder.php
Step One in Javascript
You drag the tiles into the boxes, hit the button that shows up. When you have all three, you hit the big green button. Up until this point, we are all in jQuery, and we have the following three variables stored:
wordChoiceOne - the first word you choose
wordChoiceTwo - the second word you choose
wordChoiceThree - the third word you choose
These are stored as JS variables.
Step Two PHP time
So now that I have these three stored variables I wish to move away from JS and start using PHP. I have already built a successfully working registration but it uses the username as an input rather than this when helps you "build" your own.
My research has led to the understanding that because of the client side to server side switch the only way that I can successfully pass these variables into PHP is through an AJAX request. This seems pretty handy to me because I would like the registration form I have already built to be loaded into the page asynchronously. So I asked for some advice about how to "share" these jQuery values through the AJAX request and was helped with the following, to pass them through the URL:
xmlhttp.open("GET","register-form.php?one="+wordChoiceOne+"&two="+wordChoiceTwo+"&three="+wordChoiceThree,true);
My understanding (and maybe I'm wrong? Please let me know and explain if I am...) is that this assigns the already existing variables of wordChoiceTwo etc to a PHP variable of $two. Is this right?
So now I have PHP variables $one, $two and $three...
Running the PHP
Perhaps this is because I am more used to working with JS, but with JS you have to do something (button click etc) to be able to enact a function. I know that one such do something is a successul AJAXC request but that isn't PHP. So my question... and this was really the only question I had, is ** how do you start the running of a PHP function when you've just loaded somethhing through AJAX?** I want to start running a php function called `setUsername" on this page. But I don't want the user to have to press a button to make this start, I want it to be bound to the success of the AJAX completion or something similar to this, as I understand that might be JS only.
This is the AJAX call I already have in place:
function saveUsername(wordChoiceOne, wordChoiceTwo, wordChoiceThree){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("login-register-wrapper").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","register-form.php?one="+wordChoiceOne+"&two="+wordChoiceTwo+"&three="+wordChoiceThree,true);
xmlhttp.send();
}
Add a json header type and echo
$_GET['one'], $_GET['two'] and $_GET['three'];
// Capitalise first letter
$one = ucfirst($one);
$two = ucfirst($two);
$three = ucfirst($three);
$username = $one . $two . $three;
header('Content-type: application/json');
echo json_encode(array('username'=>$username)); // <---
then in your js, bind a function to the success of the call:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//xmlhttp.responseText;
}
}
edit, because there seems to be some confusion:
Just because an ajax call reaches your php script doesn't mean it's executed. The request by nature will sit and wait for a reply. This reply can contain data if your php echo's it.
edit 2 so you can wrap your head around the principle of it, here's an oversimplification of what I think you want:
file 'ajax.html':
<div id="name"></div>
<script>
function myName(first, last) {
var req = new XMLHttpRequest();
req.open('GET', 'ajax.php?first='+first+'&last='+last);
req.onreadystatechange = function() {
if(req.readyState==4 && req.status==200) {
data = JSON.parse(req.responseText);
document.getElementById('name').innerHTML = data.username;
}
}
req.send();
}
myName('john', 'doe')
</script>
file 'ajax.php':
$first = $_GET['first'];
$last = $_GET['last'];
header('Content-type: application/json');
echo json_encode(array('username'=>ucwords($first) . ' ' . ucwords($last)));
this is generally how AJAX is used

Categories

Resources