Upload a file through a webpage to mySql database? - javascript

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

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

Can SQL Injection happen other than input Form?

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.

Storing information from php script

I m working on an html page that contains a form allowing users to enter their informations and upload files. all informations will be inserted in Mysql database.
in Javascript, im using XMLHttpRequest to send the files to the server and "upload.php" to rename (to avoid dupplicated names) and move them in the upload directory.
For better user experience, this will be done before submitting the whole form.
My question is : How can i store the new filenames (defined in upload.php)to use them in the form submission "submit.php"?
the reason for this is that in "submit.php", i insert first the user informations in "user" table and then select the "user_id" (auto increment) that will be inserted with filenames in the "files" table.
Could php sessions be an approach to do this ? is there another way? Thanks for your help
html:
<form action="submit.php" method="post" id="submitform">
<div>
<--!user info part1-->
</div>
<div id="filesContainer" class="eltContainer">
<input type="file" id="filesList" multiple>
</div>
<div>
<--!user info part2-->
</div>
javascript:
var fd = new FormData()
var xhr = new XMLHttpRequest()
for (var i=0,nb = fichiers.length; i<nb; i++) {
var fichier = fichiers[i]
fd.append(fichier.name,fichier)
}
xhr.open('POST', 'upload.php', true)
upload.php :
<?php
foreach($_FILES as $file){
$filename = date('Y') . date('m') . date('d') . date('H') . date('i') . basename($_FILES[$file]['name']);
move_uploaded_file( $file['tmp_name'],"../upload_dir/" .$filename);
}
exit;
I would consider using something like md5 for unique filenames.
Nevertheless you can push filenames into some array, and than return those filenames, as a result of post request, and put them back into some input field.
To retrieve the response simply add this lines to your code below open
xhr.onreadystatechange = function {
// If the request completed and status is OK
if (req.readyState == 4 && req.status == 200) {
// keep in mind that fileNames here are JSON string
// as you should call json_encode($arrayOfFilenames)
// in your php script (upload.php)
var fileNames = xhr.responseText;
}
}
If you'd like consider using a simple library for AJAX requests, like axios. It's promise based HTTP client for the browser, really simple to use and saves you some time and effort cause you don't have to memorize all this stuff you and I have just written.
This is one approach, but I think you can use $_SESSION as well, and it's perfectly valid. My guess is you don't have logged in user at this point, so my idea is as follows:
put filenames into the $_SESSION
use db transactions - as #Marc B suggested - to connect files with
user
if there were no errors just remove filenames from $_SESSION, if there was some, just redirect the user back to the form (possibly with some info what went wrong), and this way he doesn't have to reupload files, cause you have filenames still in $_SESSION

ASP.net and HTML File Upload

Problem: I'm working on a site written with a master page and a wrapper form. The page I'm writing needs to upload a file to the server to be validated.
What's needed: A way to submit a file without using a form and receive that form on the server in a WebMethod.
What I've tried: Using an XMLHttpRequest to send FormData to a WebMethod. The FormData is created and the file is appended like so:
let dataXML = new FormData();
dataXML.append("xml", $("#fileUpload")[0].files[0]);
sent it like this:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
// Do stuff with the request.responseText
};
request.open("POST", PageName + "/" + Route, true);
request.send(dataXML);
with a webMethod like this:
[WebMethod]
public static string myWebMethod(MultipartFormDataContent Files)
{
// Do stuff with the file
}
The WebMethod does not run at all. I'm assuming this is an issue with the WebMethod and its parameters. If I look at Page_Init() (which is run because it's returning the pages html right now rather than running my WebMethod) I can see the file in HttpContext.Current.Request.Files[0] but I don't know how to make the WebMethod run.
And before anyone says it: yes, I tried JQuery AJAX but it doesn't make a difference, the problem doesn't appear to be client side (the file was uploaded in both cases). I don't really care between JQuery AJAX and XMLHttpRequest.

Ajax request to get data from php file?

I have been researching on how to make an Ajax request and came up with this:
function ajax_post(){
// Create our XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://localhost:888...-files/test.php";
// Set content type header information for sending url encoded variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var return_data = xmlhttp.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(); // Actually execute the request
document.getElementById("demo").innerHTML = "processing...";
}
I saved this script as a file under: http://localhost:888...ascript/test.js <-- I have tested other scripts saved at this location and they work perfectly fine. My php file contains the following data (it is named "test.php"):
<?php
echo(rand(10,100));
?>
After I make the request to the php file which should display a random number according to the php code, my html looks like this:
<div style="display:none;">
<body onload="ajax_post()"> <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.
<script type="text/javascript" src="http://localhost:888...ascript/test.js"></script>
</body>
</div>
<div id="demo"></div>
I keep refreshing the page and nothing appears. Does it have to do with my php code? Perhaps my Ajax request is wrongly structured? In terms of Ajax request, I have tried "GET" and "POST" as well and still nothing happens. I am new at Ajax and the might syntax my not make sense... Thank you in advance for the support.
Regards!!
I added some html to the php file and everything loads except the php file (php appeared as a comment). Then, I came up with the idea to compare the php file I created with the other php files on my local server. I identified a little difference. The other php files do not close the php, i.e. <?php echo 'Hello World'; without putting ?> at the end, and now it works. My php file looks like this:
<?php
echo 'Hello World';
I also simplified my script, making my structure look like follows:
<div id="demo"><div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#demo').load('http://localhost:8888/...php-files/test.php');
});
</script>
I used JQuery .load() property as it is simpler than the normal script (same principle).

Categories

Resources