Empty $_FILE and $_POST superglobals when uploading via File transfer - javascript

I'm creating a mobile web app where user will be able to upload its picture and use it as an avatar. Testing it in android studio emulator everything works fine and the successful function alerts that everything is done. However my $_POST and $_FILES are empty.
JS:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
var win = function (r) {
clearCache();
retries = 0;
alert('Done!');
}
var fail = function (error) {
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Ups. Something wrong happens!');
}
alert(error);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.username = curr_username;
alert('username: ' + params.username);
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("some-server/file_upload.php"), win, fail, options, true);
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 100,
destinationType: destinationType.FILE_URI
});
}
function onFail(message) {
alert('Failed because: ' + message);
}
PHP:
<?php
$con = mysqli_connect("localhost","db_user","db_user_pw","db_name") or die(mysqli_connect_error());
// ako u javasdcriptu nemaš pristup user_id-u, treba poslat username i ovdje fetchat iz baze odgovarajući user_id
$output = print_r($_POST, true);
file_put_contents('username.txt', $output);
$output = print_r($_FILES, true);
file_put_contents('file.txt', $output);
$username = $_POST['username'];
$tmp_file_name = $_FILES["file"]["tmp_name"];
$file_name = "images/" . $username . '.jpg';
// remove the file if exists
if(file_exists($file_name)) {
unlink($file_name);
}
// upload new file
move_uploaded_file($tmp_file_name, $file_name);
$file_name = "path_to_images_folder/".$file_name;
// update database
$q = mysqli_query($con,"UPDATE users SET avatar = '$file_name' WHERE id = (SELECT id WHERE username = '$username')");
if($q)
echo "success";
else
echo "error";
?>
Any ideas why this is happening since i'm loosing my mind

Related

XMLHttpRequest stream crashing when uploading large files (~1 GB)

I'm trying to make an online file manager for another project with friends, and when uploading files bigger than 1GB, the process either crashes (firefox), or succeeds but the received file weighs 0 bytes (chromium).
JS:
function uploadFile(fileInputId, fileIndex) {
//send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
//take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onloadend = function(event) {
ajax = new XMLHttpRequest();
//send data
ajax.open("POST", 'uploader.php', true);
//all browser supported sendAsBinary
XMLHttpRequest.prototype.mySendAsBinary = function(text) {
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0)
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
if (typeof window.Blob == "function") {
var blob = new Blob([data]);
}else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}
this.send(blob);
}
//track progress
var eventSource = ajax.upload || ajax;
eventSource.addEventListener('progress', function(e) {
//percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.mySendAsBinary(event.target.result);
}
}
PHP:
//mysql login
$conn = new PDO([Redacted]);
//file info
$fileName = $_COOKIE['fname'];
$targetDir = "uploads/";
$targetFile = $targetDir.$fileName;
$fileNameRaw = explode('.', $fileName)[0]; //file name with no extension
$tempFilePath = $targetDir.$fileNameRaw.'.tmp';
if (file_exists($targetFile)) {
echo '<font color="red">Un fichier du même nom existe déjà.</font>';
exit();
}
//read from stream
$inputHandler = fopen('php://input', 'r');
//create temp file to store data from stream
$fileHandler = fopen($tempFilePath, 'w+');
//store data from stream
while (true) {
$buffer = fgets($inputHandler, 4096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
break;
}
fwrite($fileHandler, $buffer);
}
//when finished
rename($tempFilePath, $targetFile);
chmod($targetFile, 0777);
echo 'Fichier envoyé avec succès !';
$bddInsert = $conn->prepare('INSERT INTO files(nom, chemin) VALUES(?,?)');
$bddInsert->execute(array($fileName, $targetFile));
in my php.ini,
max_execution_time is set to 0
max_input_time to -1
and my post max and upload max sizes are at 4G
I'm using apache2
You should not be reading the file with the fileReader if you don't need it.
Just send the file (blob) directly to your ajax request and avoid the FileReader
function uploadFile (fileInputId, fileIndex) {
// Send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
// Take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const ajax = new XMLHttpRequest();
// send data
ajax.open("POST", 'uploader.php', true);
// track progress
ajax.upload.addEventListener('progress', function(e) {
// percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.send(file)
}

javascript - Save data in local storage into myphpadmin's database

hye.. im trying to create a quiz game but now im stuck and already spend hours to try transferring local storage data into database but still the data can't be recorded in database.
this is my js code:
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var score = $(this).val();
localStorage.setItem(id, score);
});
location.href = "wheel2.html";
});
then, to show collected marks:
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect+=10;
}
}
score.append('You got ' + numCorrect + ' marks!! ');
return score;
}
im also already try to use this code:
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "marks" + score;
xhr.open("POST", "marks.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
this is my php code:
<?php
//provide your hostname, username and dbname
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test1";
$conn = new mysqli($host, $user, $password, $dbname);
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$sql = "INSERT INTO participant (marks)
VALUES ('".$_POST['marks']."')";
{
echo"<script>alert('successfully registered')</script>".' back ';
header('location:wheel.html?message=success');
}
?>

camera photo uploaded as a File filetype with phongeap file transfer API

I'm uploading a photo taken by camera to server using file transfer API, however it's uploaded as a File filetype and the name of the photo is without the jpeg extension. The file can still be read as a image when I download, but I need to transfer the photo from the server to other API using the photo url, and the API expects to see the photo in the image filetype.
The javascript code to upload the photo:
var imgFilename = "";
//upload photo
function uploadPhoto(imageURI) {
//upload image
var fileName=imageURI.substr(imageURI.lastIndexOf('/') + 1);
//var uri = encodeURI('http://server...');
var options = new FileUploadOptions();
options.fileKey = "file";
if(fileName.indexOf('?')==-1){
options.fileName = fileName;
}else{
options.fileName = fileName.substr(0,fileName.indexOf('?'));
}
options.mimeType = "image/jpeg";//文件格式,默认为image/jpeg
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
options.headers = {Connection: "close"};
var ft = new FileTransfer();
ft.upload(imageURI, serverURL() + "/upload.php", win, fail, options);
}
function win(r){
if (imgFilename != ""){
deleteOldImg(imgFilename);
}
var arr = JSON.parse(r.response);
imgFilename = arr[0].result;
alert(r.response);
}
PHP code:
<?php
try{
$filename = tempnam('images', '');
$new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
unlink($filename);
//print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "image/user-photo/2/" . $new_image_name);
$json_out = "[" . json_encode(array("result"=>$new_image_name)) . "]";
echo $json_out;
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
The error code happens when PHP code is move_uploaded_file($_FILES["file"]["tmp_name"], 'image/user-photo/2/');

How to i get a specific value from a json encoded array?

Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}

File upload button is still not working in Cordova / Phonegap Project

Iam unable to upload pictures to a webserver with PHP backend.
My cordova camera script is able to taking the picture and show the picture in small size. But it is not able to upload an image. I dont no why. I call the function photoUpload(); and set the a onClick-event in the button like
<button class="camera-control" onclick="photoUpload();">UPLOAD</button>
Here is my JavaScript, whats wrong with it?
var pictureSource;
var destinationType;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
$("#cameraPic").attr("src", fileURI);
var win = function (r) {
clearCache();
retries = 0;
navigator.notification.alert(
'',
onCapturePhoto,
'Der Upload wurde abgeschlossen',
'OK');
console.log(r);
}
var fail = function (error) {
navigator.notification.alert(
'Bitte versuchen Sie es noch einmal.',
onCapturePhoto,
'Ein unerwarteter Fehler ist aufgetreten',
'OK');
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Fehler!');
}
}
function photoUpload() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI
});
}
function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message) {
alert('Failed because: ' + message);
}
Look your function photoUpload is located in the function onCapturePhoto! you need to move function photoUpload on the top level.
window.photoUpload = function() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
And the better way to do it like:
<button class="camera-control" id="photoUploadButton;">UPLOAD</button>
document.getElementById("photoUploadButton").addEventListener("click", photoUpload);

Categories