File won't upload to the server using PHP upload - php

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);
}
});

Related

Plupload: run uploader.php even with no image loaded

I'm using plupload to upload images in a form. When I press submit, the uploader.php does it job by uploading the images and processing the other form data using the multipart_params og pluploader.
However, I want to submit the form as well when no image is selected. When I submit with no image selected now, uploader.php simply doesn't run.
Is there a way to run uploader.php in all cases, even with no files selected?
Thanks.
This is the simplified code I'm working on:
<textarea id="textarea_input"></textarea>
<label id="browse" href="javascript:;">
<i class="fa fa-camera"></i> Add image
<span id="filelist"></span>
</label>
<a id="start-upload" href="javascript:;"">Add</a>
<span id="console"></span>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'uploader.php',
multi_selection: false,
resize: {
width: 1500,
height: 1500,
quality: 30
},
filters: {
mime_types : [
{ title : "Image files", extensions : "jpg,gif,png,jpeg" }
],
max_file_size: "10mb",
prevent_duplicates: true
},
multipart_params : {
"textarea_input" : "value1" //predefine textarea_input here, uploader right before uploader.start()
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
while (up.files.length > 1) { //custom: limit to 1 file upload.
up.removeFile(up.files[0]);
document.getElementById('filelist').innerHTML = '';
}
var html = '';
plupload.each(files, function(file) {
html += '<br /><span id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></span>';
});
document.getElementById('filelist').innerHTML += html;
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
});
uploader.bind('UploadComplete', function(up, files) {
window.location = "mobilelogbook.php?saved=2";
});
document.getElementById('start-upload').onclick = function() {
uploader.settings.multipart_params["textarea_input"] = document.getElementById("textarea_input").value;
uploader.start();
};
</script>
And the uploader.php:
<?php
if (empty($_FILES) || $_FILES["file"]["error"]) {
$fileName = '';
} else {
$fileName = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "images/logbook/$fileName");
}
if (isset($_POST['textarea_input'])) {
$log = $_POST['textarea_input'];
} else {
$log = '';
}
// SQL GOES HERE: ADDS THE TEXTAREA_INPUT AND FILENAME TO A TABLE.
die('{"OK": 1}');
?>

Upgrade PHP...then... error with file upload file

I'm not a php programmer. Someone ask me help for a web server with problem. I fix everything and update PHP 5.4 to 5.6. Everything work fine on his php program, except file upload.
Message: getimagesize(var/www/myserver/admin/uploads/temp/test.jpg): failed to open stream: No such file or directory
error on this line: $img_info = getimagesize("uploads/temp/$filename");
if($_POST['fileselect'][0] != "")
$filename=$_POST['fileselect'][0];
else
$filename=$_POST['dragfile'];
if(strlen($filename) > 3){
$finalname=time(); //Set a unique filename by the UNIX time
//Convert to jpg if tiff
$img_info = getimagesize("uploads/temp/$filename");
if($img_info['mime'] == "image/tiff"){
$clearname=explode(".", "$filename")[0];
system("convert uploads/temp/\"$filename\"[0] uploads/temp/$clearname.jpg");
unlink("uploads/temp/$filename");
$filename=$clearname.".jpg";
}
The problem probably come from a new code formulation in php5.6, any idea how to fix that ?
UPDATE 2: FILE UPLOAD section...
part of form.php
<form method="post" class="form-horizontal">
<input type="hidden" id="to_upload" name="to_upload" value="/upload.php">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000000" />
<input type="hidden" id="id_produit" name="id_produit" value="<?php echo $this->mdl_inventory->form_value('idproduit'); ?>" />
<div class="control-group">
<label class="control-label">Nouveau (jpeg): </label>
<div class="controls">
<input type="file" id="fileselect" name="fileselect[]">
</div>
</div>
Does the name fileselect[] can be the problem ? How can i check if the script go in "upload.php" ?
part of upload.php
/* read the source image */
$source_image = imagecreatefromjpeg("$src");
$width = imagesx($source_image);
$height = imagesy($source_image);
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/temp/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
ajax script filedrag.js (upload)
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/tiff" ) && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("to_upload").value + "?idproduit=" + $id("id_produit").value, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
$('#dragfile').attr('value', file.name);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The syntax for the code mentioned is correct for 5.6, no issues with that.
I don't see permissions as the issue as well, otherwise you'd have gotten a 'Permission denied' error.
So, most likely, it looks like, the file that you are looking for does not exist in the folder.
the error was here:
xhr.setRequestHeader("X_FILENAME", file.name);
X-filename... i think it's APACHE UPDATE problem.
Thanks for help.

json - Form success message not showing on successful submission with PHP

I have difficulty in showing success message on form. Its showing all the error messages but not the success message.
On controller file its showing when I comment $this->model_catalog_outofstockquery->addQuery($this->request->post);
but this line is necessary.
On submitting form the entries are successfully loading to the database.
I have already call model from the constructor
My code on controller file is-
public function write() {
$this->load->language('product/outofstock_enquiry');
$json = array();
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
$json['error'] = $this->language->get('error_name');
}
if (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
$json['error'] = $this->language->get('error_email');
}
if ((!filter_var($this->request->post['quantity'],FILTER_VALIDATE_INT))) {
$json['error'] = $this->language->get('error_quantity');
}
if (!isset($json['error'])) {
$json['success'] = $this->language->get('text_success');
$data['product_id'] = $this->request->post['product_id'];
$data['product_name'] = $this->request->post['product_name'];
$data['name'] = $this->request->post['name'];
$data['email'] = $this->request->post['email'];
$data['quantity'] = $this->request->post['quantity'];
$data['notify'] = 0;
$this->model_catalog_outofstockquery->addQuery($this->request->post);
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The script on the view file under the form is
<script type="text/javascript"><!--
$('#button-submit').on('click', function() {
$.ajax({
url: 'index.php?route=product/outofstock_enquiry/write&product_id=<?php echo $product_id; ?>',
type: 'post',
dataType: 'json',
data: 'name=' + encodeURIComponent($('input[name=\'name\']').val()) + '&email=' + encodeURIComponent($('input[name=\'email\']').val()) + '&product_name=' + encodeURIComponent($('input[name=\'product_name\']').val()) + '&quantity=' + encodeURIComponent($('input[name=\'quantity\']').val()) ,
data: $("#form-ask").serialize(),
beforeSend: function() {
$('#button-submit').button('loading');
},
complete: function() {
$('#button-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
if (json['error']) {
$('#outofstock_enquiry').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#outofstock_enquiry').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '</div>');
$('input[name=\'name\']').val('');
$('input[name=\'email\']').val('');
$('input[name=\'product_name\']').val('');
$('input[name=\'quantity\']').val('');
$('input[name=\'product_id\']').val('');
}
}
});
});
//--></script>

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

Categories