File not uploading to the server - php

I am trying to upload a file using ExtJS and PHP.
My file is not uploading to the server.
JS:
function slidersave(){
var form = sliderform.getForm();
if (form.isValid()) {
var slider_name=Ext.getCmp('txtslidername').getValue();
var slider_image=Ext.getCmp('txtsliderimage').getValue();
var slider_link=Ext.getCmp('txtsliderurl').getValue();
form.submit({
url: 'slider/file',
waitMsg: 'Uploading your slider image...',
success: function(form, o) {
var obj = Ext.util.JSON.decode(o.response.responseText);
alert(obj);
if (obj.failed == '0' && obj.uploaded != '0') {
Ext.Msg.alert('Success', 'All files uploaded');
} else if (obj.uploaded == '0') {
Ext.Msg.alert('Success', 'Nothing Uploaded');
} else {
Ext.Msg.alert('Success',
obj.uploaded + ' files uploaded <br/>' +
obj.failed + ' files failed to upload');
}
}
});
}
}
PHP:
public function file()
{
if(isset($_FILES)){
$uploaddir = '/siteimages/slider/';
$uploadfile = $uploaddir . basename($_FILES['txtsliderimage']['name']);
if (move_uploaded_file($_FILES['txtsliderimage']['tmp_name'], $uploadfile)) {
echo '{success: true}';
} else {
echo '{success: false}';
}
}
}
I am not getting anything in the response the loader just disappears after sometime.
I don't know what's happening.

Related

How to create php multiple file zone upload?

I have on my website upload.php file please I want to use this script on my server which controls the upload of files to the server and can only upload one file.
Now I would like to do a multiple file upload with a drop zone just like here:
Multiple file Upload
As far as I know, I can set up a javascript and html form, but I don't know how to modify my upload.php file, which controls the upload of files to the server. Please see below is my upload.php file that controls the upload of one file how to modify it so that multiple files can be uploaded at once with the script whose link I left above:
<?php
$error_message = "";
$success_message = "";
if (IS_POST()) {
if ($_FILES['upload']) {
$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$type = getFileTypeText($_FILES['upload']['type']);
$ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
$user = getUserFromSession();
$userId = $user->id;
if (!file_exists(ABSPATH . '/content/uploads/'.$userId.'/'.$name)) {
$acceptedExt = ['srt', 'ass', 'sub', 'sbv', 'vtt', 'stl'];
if (in_array($ext, $acceptedExt)) {
$db_name = GET_GUID() . "." . $ext;
$file_name_db = ABSPATH . '/content/uploads/' . $userId . '/' . $name;
$description = isset($_POST["description"]) && $_POST["description"] != '' ? $_POST["description"] : $name;
if ($size > 0) {
move_uploaded_file($_FILES['upload']['tmp_name'], $file_name_db);
chmod($file_name_db, 0666);
$id = db_insertUploadDetails($name, $description, $size, $userId, $ext, $name);
if ($id > 0) {
$success_message = "Uploaded successfully.";
echo "<script>location.href='list.php';</script>";
}
} else {
$error_message = "Not a valid file.";
}
} else {
$error_message = "Please upload only srt, ass, sub, sbv, vtt, stl";
}
}else{
$error_message="File Already Exists";
}
}
}
So your point is like ,you want to upload multiple files in series right.Use ajax to send it one after another and this will work.No need of any edits.
<!DOCTYPE html>
<html>
<head>
<title>Drag and drop Multiple files</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3>Drag and drop multiple file upload </h3><br />
<div id="drop_file_area">
Drag and Drop Files Here
</div>
<div id="uploaded_file"></div>
</div>
</body>
</html>
Use some css to tidy up the things.
ajax will be like this
<script>
$(document).ready(function () {
$("html").on("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
$("html").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
});
$('#drop_file_area').on('dragover', function () {
$(this).addClass('drag_over');
return false;
});
$('#drop_file_area').on('dragleave', function () {
$(this).removeClass('drag_over');
return false;
});
$('#drop_file_area').on('drop', function (e) {
e.preventDefault();
$(this).removeClass('drag_over');
var formData = new FormData();
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
formData.append('file[]', files[i]);
}
uploadFormData(formData);
});
function uploadFormData(form_data) {
$.ajax({
url: "upload.php",
method: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$('#uploaded_file').append(data);
}
});
}
});
</script>
this will be the upload.php .db_config will be your db connect file
<?php
// Include the database connection file
include('db_config.php');
$fileData = '';
if(isset($_FILES['file']['name'][0]))
{
foreach($_FILES['file']['name'] as $keys => $values)
{
$fileName = $_FILES['file']['name'][$keys];
if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'uploads/' . $values))
{
$fileData .= '<img src="uploads/'.$values.'" class="thumbnail" />';
$query = "INSERT INTO uploads (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
mysqli_query($con, $query);
}
}
}
echo $fileData;
?>
sanitizing the data is upto you.This is just an example

AJAX data displays different variable than PHP return

I have the PHP function:
public function add() {
$image = $this->input->post('image');
$headers = $this->travel_model->getFunction('headers');
//Add new uploaded image
if (!empty($_FILES['img']['name'])) :
//Check uploaded file extension
$file_parts = pathinfo($_FILES['img']['name']);
$ext = $file_parts['extension'];
if($ext == "jpg" || $ext == "jpeg" || $ext == "png") {
$image = md5($_FILES['img']['name']) . "." . $ext;
$img = ROOT.'resources/img/headers/'.$image;
move_uploaded_file($_FILES['img']['tmp_name'], $img);
$result = "passed";
} else {
$result = "error-img-format";
}
else :
$result = "passed";
endif;
//Check if is new added slideshow or editable slideshow
if($result != "error-img-format") {
if($this->input->post('id')) {
$this->headers_model->updateHeaders($image);
} else {
//Check if more than three slides and Delete the last slide
foreach($headers as $key => $hdr) {
if($key >= 2) {
$this->travel_model->deleteFunction($hdr->id, 'slideshows') ;
}
}
$this->headers_model->insertHeaders($image);
}
}
echo $result;
}
Uploaded an img with extensions different than .jpg, .jpeg or .png, PHP displays: error-img-format as it should do
JQuery:
$(document).ready(function () {
$('#add_headers').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/backend/headers/add',
data: $(this).serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
});
Alert displays passed, different than PHP does. Can't understand what's the problem..

Ajax request returns nothing. why?

Below is the ajax request.
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){
if(undeleted == 0) {
alert('All ' + deleted + ' files delted from the server');
} else {
alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');
}
}, 'json');
and here goes the delete.php
<?php
if(isset($_POST['deletearray'])) {
$files = $_POST['deletearray'];
$dir = $_POST['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
echo json_encode($deleted, $undeleted);
}
return;
?>
Up on running the code it deletes the files successfully but no message displays.
I also tried changing the ajax request as:
$.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){
alert("php finished");
}, 'json');
still it does not display the message. So i guess something is wrong in the delete.php file. Please help.
First thing-
Use $_POST['deletearray'] instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}
The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>
You should use json_encode like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');

Upload a file using AJAX and PHP

I'm trying to make a script to upload files to my server.
What's really bothering me is that the success call is executed though the file is not uploaded.
HTML
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<label>Castellà</label><input name="mapa_es" id="mapa_es" type="file" />
<div id="progressbox_es" style="display:none;">
<div id="progressbar_es">
<div id="statustxt_es">0%
</div>
</div>
</div>
</form>
JS
$(document).ready(function() {
$('#mapa_es').change(function() {
var formData = (this.files[0]);
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
console.log(percentComplete + '%');
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%')
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%');
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
console.log(percentComplete + '%');
}
}, false);
return xhr;
},
url: 'processupload.php',
type: 'POST',
data: formData,
async: true,
beforeSend: function() {
},
success: function(msg) {
console.log(msg);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
and the PHP code in processupload.php
<?php
if (isset($_FILES["mapa_es"]) && $_FILES["mapa_es"]["error"] == UPLOAD_ERR_OK) {
$UploadDirectory = 'mapes/';
if ($_FILES["mapa_es"]["size"] > 5242880) {
echo "File size is too big!";
}
$File_Name = strtolower($_FILES['mapa_es']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.'));
$Random_Number = rand(0, 9999999999);
$NewFileName = $Random_Number . $File_Ext;
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded.';
} else {
echo 'error uploading File!';
}
} else {
echo 'Something wrong with upload!';
}
?>
I will appreciate any help you could give me. Thanks.
EDIT: I followed gtryonp suggestions and I got into more problems.
When I try to var_dump($_FILES) all I get is an empty string.
I also tried to submit the form using $().submit instead on $().change and it worked, I think it may be because of "enctype="multipart/form-data" on the form tag.
Is there any way to achieve it without having to submit the whole form?
Your processupload.php is ending with a die(message) and will be take as a normal program end, so the success event will be fired and the console.log('FILE UPLOADED') will be your response always, even in error cases. Change all your die(message) with echo message, something like:
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded to '.$UploadDirectory . $NewFileName;
} else {
echo 'error uploading File!';
}
...
and change the success function for something that echoes the possible answers to your screen. Something like:
success: function(msg) {
console.log(msg);
},
HAGD

File won't upload to the server using PHP upload

I'm trying to get file uploads working on my inventory system but can't seem to get it working. I am using Lite Uploader and PHP.
Here is my upload.php file:
<?php
require('../../includes/config.php');
$urls = array();
if (isset($_POST['liteUploader_id']) && $_POST['liteUploader_id'] == 'fileUpload1'){
foreach ($_FILES['fileUpload1']['error'] as $key => $error){
if ($error == UPLOAD_ERR_OK){
$uploadedUrl = $var['site_url'].'assets/images/uploads/' . $_FILES['fileUpload1']['name'][$key];
move_uploaded_file( $_FILES['fileUpload1']['tmp_name'][$key], $uploadedUrl);
$urls[] = $uploadedUrl;
}
}
if(file_exists($uploadedUrl)){
$message = "Successfully uploaded file.";
} else {
$message = "File did not upload properly.";
}
}
echo json_encode(
array(
'message' => $message,
'urls' => $urls,
)
);
exit;
?>
It appears that the file is not being moved once temporarily uploaded as there is no image shown on chrome when uploaded.
If you need any other files let me know. Thanks a lot!
EDIT:
Here is the upload form code:
<input type="file" name="fileUpload1" id="fileUpload1" class="fileUpload" />
<div id="details"></div>
<div id="response"></div>
<div id="previews"></div>
The form is done through javascript with the following code:
jQuery('.fileUpload').liteUploader({
script: 'libraries/lite_uploader/upload.php',
allowedFileTypes: 'image/jpeg,image/png,image/gif',
maxSizeInBytes: 250000,
customParams: {
'custom': 'tester'
},
before: function (files)
{
jQuery('#details, #previews').empty();
jQuery('#response').html('Uploading ' + files.length + ' file(s)...');
},
each: function (file, errors)
{
var i, errorsDisp = '';
if (errors.length > 0)
{
jQuery('#response').html('One or more files did not pass validation');
jQuery.each(errors, function(i, error)
{
errorsDisp += '<br /><span class="error">' + error.type + ' error - Rule: ' + error.rule + '</span>';
});
}
jQuery('#details').append('<p>name: ' + file.name + ', type: ' + file.type + ', size:' + file.size + errorsDisp + '</p>');
},
success: function (response)
{
var response = jQuery.parseJSON(response);
jQuery.each(response.urls, function(i, url)
{
jQuery('#previews').append(jQuery('<img>', {'src': url, 'width': 200}));
});
jQuery('#response').html(response.message);
}
});

Categories