I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:
undefined index archivo
This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)
function Registrar() {
var cat = $('#cat').val();
var nom = $('#name').val();
var desc = $('#description').val();
var image = $('#archivo').val();
//Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
success: function (data) {
console.log(data);
}
});
}
PHP file:
<?php
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_POST['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
And the important parts of my HTML:
<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
EDIT: showimagepreview
function showimagepreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
How can I solve this?
Send your form data like this:
var formData = new FormData($("form")[0]);
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: formData,
success: function (data) {
console.log(data);
}
});
And you have to get the file with $_FILES, you can not get it in $_POST in php code.
Here is you solution
HTML
<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>
Java Script
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
//ajax
$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});
PHP
<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
change this
$img = $_POST['archivo'];
to
$_FILES['archivo'];
Files object cannot be recieved in $_POST
Related
im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);
I have been able to implement Live Search to my XHTML page. But I have 2 issues:
I want it to return more than one item, which I have not been able to do and is very important.
I want to capitalize the first letter from each word, since if I search with a uppercase letter, that letter in every word turns uppercase. I tried with CSS capitalize but that gives no results in the input box.
This is my code:
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
This is what I tried but is not working in addition to the code above:
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.telefone').html();
var decoded = $("<div/>").html($name).text();
$('#searchid1').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search1")){
jQuery("#result").fadeOut();
}
});
$('#searchid1').click(function(){
jQuery("#result").fadeIn();
});
And this is the PHP:
$strSQL_Result = mysqli_query($connection,"select Nome,Email,Telefone from Contactos where Nome like '%$q%' order by Nome LIMIT 15");
while($row=mysqli_fetch_array($strSQL_Result))
{
$username = $row['Nome'];
$b_username = '<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$telefone = $row['Telefone'];
$b_telefone = '<strong>'.$q.'</strong>';
$final_telefone = str_ireplace($q, $b_telefone, $telefone);
?>
<div class="show" align="left">
<span class="name"><?php echo $final_username; ?></span> <br/>
<span class="telefone"><?php echo $final_telefone; ?></span> <br/>
</div>
I have a button that when clicked is supposed to submit variables to an ajax call which then a csv is created and downloaded but for some reason the file just isnt downloading. Yet I get the correct output in Chrome Dev tools:
Here is what I have:
index.php
<form class="navbar-form navbar-left" method="post">
<input hidden id="ajaxquery" value="<?php echo $ajaxquery;?>">
<button type="button" class="btn btn-success btn-lg" id="downloadcsv">Download CSV</button>
</form>
script.js
$(document).ready(function() {
var csvquery = function(){
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
ajaxquery = $('#ajaxquery').val();
department = getUrlParameter('department');
startdate = getUrlParameter('startdate');
enddate = getUrlParameter('enddate');
staffsearch = getUrlParameter('staffsearch');
$.ajax({
type: 'POST', // type
url: '../report/csv.php', // request file the 'check_email.php'
data: {ajaxquery:ajaxquery, department: department, startdate:startdate, enddate: enddate, staffsearch: staffsearch},
success: function(responseText) {
}
}); // end success
}
$('#downloadcsv').click(csvquery);
});
csv.php
session_start();
require '../connect.php';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Name', 'Department','Hours Worked', 'On Holiday', 'Ill' , 'Date'));
$sql = "SELECT time.id as timeid, time.staff_id, time.timein, time.onholiday, time.dateadded, time.ill, time.notes, staff.id AS staffid, department.id AS departmentid, department.department_name, staff.staff_name, staff.department_id FROM time, staff, department WHERE staff.id = time.staff_id AND staff.department_id = department.id ORDER BY `time`.`dateadded` ASC ;";
$rows = mysqli_query($connect, $sql);
while ($rowcsv = mysqli_fetch_assoc($rows)){
fputcsv($output, array($rowcsv['staff_name'],$rowcsv['department_name'],$rowcsv['timein'],$rowcsv['onholiday'],$rowcsv['ill'],$rowcsv['dateadded']));
};
readfile("php://output");
Change aJax to fileDownload:
$.fileDownload('../report/csv.php', {
httpMethod: 'POST',
data: {
ajaxquery:ajaxquery, department: department, startdate:startdate, enddate: enddate, staffsearch: staffsearch
},
successCallback: function (url) {
//insert success code
},
failCallback: function (html, url) {
//insert fail code
}
});
You can use jQuery fileDownload method through this js file:
https://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js
More information at:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
So I am working on this project where I have to make a photo sharing site, I select the photos and then upload them, send the link via email, and then the person goes on the link and downloads the photos. Everything works great when I have few photos and when not exceeding 100MB of data, when I go beyond that everything becomes unstable.
First of I am using HTML5's FileReader().The logic is the following:
I use FileReader() to transform each photo into a base64 code and every 3 photos transformed I send a 3 photos long base64 string via Ajax to a php file which then transforms the code into photos and uploads them into a folder on the server.
If I have 300 photos selected I do 100 ajax requests.
The first problem if if I exceed ~150MB of data ajax will give me an uncaught exception out of memory error.
The second problem is if I chose over 20-30 files the brower some times gets unresponsive even crashes..
Any suggestions what can I do ? Maybe the whole idea is wrong and I should start somewhere else, please help.
This is the code:
//Forming the inputs
$(document).on("change","#fileUp",function(e){
var file = null;
var files = e.target.files; //FileList object
var picReader = new FileReader();
$(".eventPop").html("");
$(".howMany").html("");
$(".eventPop").show();
$(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');
countUp = parseInt(countUp) + parseInt(files.length);
for(var i=0; i<=files.length-1; i++){
file = files[i];
var str = file.name.split(".")[0];
//
//var picReader = new FileReader();
if (file.type == "image/jpeg" || file.type == "image/png")
{
picReader.addEventListener("load",function(event){
count++;
var picFile = event.target;
$(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
});
}
else
{
countUp--;
}
picReader.readAsDataURL(file);
}
});
//actual ajax requests
$(document).on('click','.uploadImages',function(){
info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
$.ajax({
type: "POST",
url: "index/loadIntoDB",
dataType:"text",
data: {info: info},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
}
});
if (nrConfig > count)
{
nrConfig = count;
}
$(".eventPop").show();
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
for(var i=1; i<=parseInt(nrConfig)+1; i++)
{
if (i == parseInt(nrConfig)+1)
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,1);
}
else
{
//info[0] = i+"-"+info[0];
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
});
function uploadImages(i,d){
info['3'] = i;
info['4'] = d;
$.ajax({
type: "POST",
url: "index/receiveImages",
dataType:"json",
data: {info : info },
beforeSend : function (){
//
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
{
if (result[index]['filesize'] < 1000000)
{
result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
else
{
result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
if (result[index]['filesize'].length > 0)
{
$("#ph"+result[index]['id']+" .uploading").remove();
$("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
$("#ph"+result[index]['id']+" .upd").remove();
}
}
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');
if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
{
setTimeout(function(){
$("progress").remove();
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'>Upload complete!</div>");
setTimeout(function(){
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas#gmail.com ; peter#gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
},1000);
},1000);
}
if (info[2].length)
{
info[2] = "";
}
if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
{
nrConfig = count-result['info']['4']+1;
}
if(result['info']['4'] <= count)
{
for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
{
if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,result['info']['4']);
}
else
{
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
}
}
});
}
PHP code:
public function receiveImages()
{
$string = strtok($_POST['info'][2],"--");
$currentID = $_POST['info']['4'];
$newArray['info']['3'] = $_POST['info']['3'];
$newArray['leftOff']['1'] = $currentID;
$phAdded = 0;
while($string != false && $phAdded < $_POST['info']['3'])
{
$newArray[$currentID]['id'] = $currentID;
$newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
$currentID++;
$phAdded++;
$string = strtok("--");
}
$newArray['info']['4'] = $currentID;
echo json_encode($newArray);
}
public function saveImages($base64img = "",$folder = "",$currentID = "")
{
$newArray = array();
if (!is_dir(UPLOAD_DIR.$folder))
{
mkdir(UPLOAD_DIR.$folder,0777);
}
$dir = UPLOAD_DIR.$folder."/";
if (strstr($base64img,'data:image/jpeg;base64,'))
{
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.jpg';
$file_name = $uniqid.".jpg";
}
else
{
$base64img = str_replace('data:image/png;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.png';
$file_name = $uniqid.".png";
}
$data = base64_decode($base64img);
file_put_contents($file, $data);
$size = filesize($file);
if ($size > 1000000)
{
$size = number_format(($size/1000000),2)."MB";
}
else
{
$size = number_format(($size/1000),0)."kb";
}
return filesize($file);
}
First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.
So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981
So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.
So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?
Ideal would be either a prefix for the file name or store everything in it's own folder.
I tried several things but my knowledge is limited, so any help greatly appreciated.
The upload script:
//Start the upload code.
........
......
if(sizeof($_FILES)===0){
echo "<li>No files were uploaded.</li>";
return;
}
foreach ($_FILES['ufiles']['name'] as $key => $value) {
if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
return;
}
$tmpDir = uniqid('/tmp/DropboxUploader-');
if (!mkdir($tmpDir)) {
echo 'Cannot create temporary directory!';
return;
}
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
return;
}
try {
$uploader = new DropboxUploader($drop_account, $drop_pwd );
$uploader->upload($tmpFile, $drop_dir);
echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;
// Clean up
if (isset($tmpFile) && file_exists($tmpFile))
unlink($tmpFile);
if (isset($tmpDir) && file_exists($tmpDir))
rmdir($tmpDir);
} catch(Exception $e) {
$error_msg = htmlspecialchars($e->getMessage());
if($error_msg === 'Login unsuccessful.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
return;
}
if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
return;
}
echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
}
}
UPDATE AS REQUESTED
The form:
<form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
<fieldset>
<div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
</fieldset>
<button type="button" id="ubutton">Upload</button>
<button type="button" id="clear5" onclick="ClearUpload();">Delete</button>
<input type="hidden" name="id" id="prefix" value="" />
</form>
Upload.js (file is downloadable as free script on the internet):
(function () {
if (window.FormData) {
var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
formdata = new FormData();
thefiles.addEventListener("change", function (evt) {
var files = evt.target.files; // FileList object
var i = 0, len = this.files.length, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (isValidExt(file.name)) { //if the extension is NOT on the NOT Allowed list, add it and show it.
formdata.append('ufiles[]', file);
output.push('<li>', file.name, ' <span class="exsmall">',
bytesToSize(file.size, 2),
'</span></li>');
document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
}
}
document.getElementById('filemsg').innerHTML = '';
document.getElementById('filemsgwrap').style.display = 'none';
document.getElementById('ubutton').style.display = 'inline-block';
document.getElementById('clear5').style.display = 'inline-block';
}, false);
upload.addEventListener('click', function (evt) { //monitors the "upload" button and posts the files when it is clicked
document.getElementById('progress').style.display = 'block'; //shows progress bar
document.getElementById('ufileform').style.display = 'none'; //hide file input form
document.getElementById('filemsg').innerHTML = ''; //resets the file message area
$.ajax({
url: 'upload.php',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (results) {
document.getElementById('ufileform').style.display = 'block';
document.getElementById('progress').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'block';
document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
document.getElementById('ufiles').value = '';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
formdata = new FormData();
output.length = 0;
}
});
}, false);
} else {
// document.getElementById('passarea').style.display = 'none';
document.getElementById('NoMultiUploads').style.display = 'block';
document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></li><li><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></li><li><img src="images/apple-safari-logo.png" alt="Apple Safari" /></li><li><img src="images/maxthon-logo.png" alt="Maxthon" /></li></ul>';
}
document.getElementById('multiload').style.display = 'block';
document.getElementById('ufileform').style.display = 'block';
}());
function ClearUpload() { //clears the list of files in the 'Files to Upload' area and resets everything to be ready for new upload
formdata = new FormData();
output.length = 0;
document.getElementById('ufiles').value = '';
document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'none';
}
function getExtension(filename) { //Gets the extension of a file name.
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isValidExt(filename) { //Compare the extension to the list of extensions that are NOT allowed.
var ext = getExtension(filename);
for(var i=0; i<the_ext.length; i++) {
if(the_ext[i] == ext) {
return false;
break;
}
}
return true;
}
Change this line
$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
Note the $_POST['id'] which was added
EDIT: Changed to $_POST
Also in your form which you are posting add
<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />
You could simply at time() to your file name.
http://php.net/manual/de/function.time.php
$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);