PHP & AJAX Upload File Fails Some times - php

I am creating a simple video uploader for an adults site and it works for small files but it doesn't for bigger files. I have not tested what the break line is but I know for sure it works for 5mb or so file and fails for 100mb+ files. In the server I have set the maximum upload size and maximum post size to 1000mb in the php5.ini. Can you spot anything wrong with the code or do you think this is a server problem? The site is being hosted in a linux godaddy server. Here is a link for testing:
http://munchmacouchi.com/upload_sample/upload.php
Here is the code in upload.js:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax',true);
for ( var i = 0 ; i < fileInput.files.length ; i++ ){
data.append('file[]',fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total ;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes())
progress.removeChild(progress.firstChild);
progress.appendChild(document.createTextNode(Math.round(percent*100)+' %'));
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display='none';
});
request.upload.addEventListener('error', function(event){
alert('Upload Failed');
});
request.addEventListener('readystatechange', function(event){
if(this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for(var i = 0 ; i < uploaded.length ; i++){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href','files/'+uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log("Server replied with HTTP status " + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display='block';
request.send(data);
}
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});
and for upload.php:
<?php
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Test</title>
<h3>Upload Test</h3>
<script type="text/javascript" src="upload.js"></script>
<style type="text/css">
#upload_progress {display:none;}
</style>
</head>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded)){
foreach($uploaded as $name){
echo '<div>', $name , '</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file[]" multiple="multiple"/>
<input type="submit" id="submit" value="Upload"/>
</div>
</form>
</div>
</body>
</html>

Related

Dropzone file upload new name?

Here is what my user interface looks like:
Here is my code. I want to change the file name when the file is uploaded.
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>LCW DOSYA UPLOAD V1.0</title>
<link rel="stylesheet" href="dropzone.css"/>
<script src="dropzone.js"></script>
</head>
<body>
<center>
<label for="belge">Belge No:</label><br><br>
<input type="text" id="belge" name="belge"><br>
<br>
<input type="radio" id="ups" name="gender" value="ups">
<label for="ups">UPS</label><br>
<input type="radio" id="fillo" name="gender" value="fillo">
<label for="fillo">Fillo</label><br></center><br><br>
<form action="upload.php" class="dropzone" id="my-awesome-dropzone">
</form>
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 20000, // MB
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
return newName;}
};
</script>
</body>
</html>
upload.php
<?php
$dizin="images/";
$kaynak=$_FILES["file"]["tmp_name"];
$hedef=$dizin.$_FILES["file"]["name"];
if(move_uploaded_file($kaynak,$hedef)==true){
echo 'Yukleme Basarili';
}else {
echo 'HATA';
}
?>
The file name should be: belge + radio + 'filename.jpg'
What should I to make it should happen when I upload files?
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 20000, // MB
renameFile: function (file){
var belge = document.getElementById('belge').value;
var radios = document.getElementsByName('gender');
for(var i = 0, length = radios.length; i < length; i++){
if(radios[i].checked){
var radio = radios[i].value;
}
}
let newName = belge + '_' + radio + '_' + file.name;
return newName;
}
};
</script>

How to upload multiple images to a folder using ajax php and jquery

I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload.
If I am uploading a single image without loop then its working fine but in case of loop it's not working.
I am using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
for (var i = 0; i < $('#file').get(0).files.length; ++i) {
names.push($('#file').get(0).files[i].name);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
//PHP Code
<?php
/* Getting file name */
echo "<script>alert('yes');</script>";
//without loop working fine
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file']['name'][$i];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'],$_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
In the loop you will need to add index of particular file
move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index

How to detect the number of uploaded files and their names before uploading from client side by javascript or jquery?

I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10

File Upload Progress for Dynamic Dropdown File Upload

I have made a dynamic dropdown file upload system where user can choose the engineering stream, then the semester and then subject, and the file gets uploaded in the desired directory. This works fine normally. I came across the Javascript/AJAX File Upload Progress tutorial from PHPAcademy, things worked fine until I got stuck into this.
Without adding the javascript file (for upload progress), the files get uploaded in the correct directory, show no errors in the firebug, and also gives the link to the file after it gets uploaded.
But after I add the JS file, the link doesn't come after upload, it gets uploaded in the root directory always, it shows the progress though, and the console shows two errors.
Here is my PHP code:
<?php
if(isset($_POST['upload'])) {
$path1=$_POST['one']."/";
$path2=$_POST['two']."/";
$path3=$_POST['three']."/";
$upload_path=$path1.$path2.$path3;
}
else {
echo "Follow the instructions before uploading a file";
}
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], $upload_path."$name")) {
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])) {
die(json_decode($uploaded));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> SRMUARD - Upload </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
function val()
{
if(document.uploads.three.selectedIndex == 0)
{
alert("Please choose all the appropriate options");
}
}
</script>
<script>
$(function() {
$("#text-one").change(function() {
$("#text-two").load("textdata/" + $(this).val() + ".txt");
});
$("#text-two").change(function() {
$("#text-three").load("textdata/" + $(this).val() + ".txt");
});
});
</script>
</head>
<body>
<div value="<?php $upload_path ?>" id="uploadpath"></div>
<div id="uploaded">
<?php
if(!empty($uploaded)) {
foreach($uploaded as $name) {
echo 'File Link: '.'<a href="' . $upload_path . $name . '" >', $name, '</a><br/>';
}
}
?>
</div>
<div id="upload_progress" style="display: none"></div>
<div>
<form action="" method="POST" enctype="multipart/form-data" name="upload" id="upload">
<label for="file">Choose a file: </label><br/>
<input type="file" name="file[]" id="file" multiple="multiple"><br/><br/>
<select id="text-one" name="one">
<option selected value="base">Select Department</option>
<option value="CSE" name="cse">Computer Science Engineering</option>
<option value="ECE" name="ece">Electronics & Communication Engineering</option>
<option value="MECH" name="mech">Mechanical Engineering</option>
</select><br/><br/>
<select id="text-two" name="two"> //Displays options dynamically using text files
<option>Select Semester</option>
</select><br/><br/>
<select id="text-three" name="three"> //Displays options dynamically using text files
<option>Select Subject</option>
</select><br/><br>
<input type="submit" name="upload" id="submit" value="Upload" onClick="val()" />
</form>
<div>
</body>
</html>
And here is my javascript code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for(var i = 0; i < fileInput.files.length; ++i) {
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed due to some reason!');
});
request.addEventListener('readystatechange', function(event) {
if(this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
var phpval = document.getElementById('uploadpath').value;
for(var i=0; i < uploaded.length; ++i) {
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', phpval + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load',function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And the errors shown in the console are:
TypeError: document.uploads is undefined
[Break On This Error]
if(document.uploads.three.selectedIndex == 0)
and
SyntaxError: missing ; before statement upload.js file line 47 which is var uploaded = eval(this.response);
And another place where I feel I am making a mistake is:
a.setAttribute('href', phpval + uploaded[i]);
The phpval must correspond to the dynamic upload link. I couldn't use the $upload_path in the JS, so made a div out of it, and then used to get the value like this:
var phpval = document.getElementById('uploadpath').value;
For the demo, you can refer this link, things will be more precise, please turn on your firebug console and check the errors and help me. I am not able to solve this.
Dynamic Dropdown File Upload with Progress Indication
Thank You
Also consider positioning of your script properly. Sometimes what happens is the place where you place your script might cause conflicts. I can see that you have the scripts for Dynamic Dropdown Functionality already. Try placing it after your form and check if it works.
Hope this helps.
There are many JQuery options you could try. Here is one from Blueimp. Hope this helps.

Click on HTML element on iframe [duplicate]

This question already exists:
Closed 11 years ago.
Possible Duplicate:
Get xpath location of element in iframe(iframe from my domain)
I have a javascript function to get xpath as result (getXPath) and below is the code. Also I have a an external site in iframe but I show him when I use proxy (code is below). And I have a jquery function to show me xpath when I click on some element in iframe but Dont work. What is problem:
CODE:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$url = $_GET['url'];
if( ! empty($url))
{
$data = file_get_contents($url);
$data = str_replace('<head>', '<head><base href="'.$url.'" /></base>', $data);
$data = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $data);
$data = preg_replace('#<iframe(.*?)></iframe>#is', '', $data);
$data .=
'
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("div").each(function(i){
if($(this).css("position") == "fixed") $(this).css("display", "none");
});
</script>
'
;
die($data);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="Webarto" />
<title>AdriaMart</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
//function for xpath location
<script type="text/javascript">
function getXPath(node, path) {
path = path || [];
if(node.parentNode) {
path = getXPath(node.parentNode, path);
}
if(node.previousSibling) {
var count = 1;
var sibling = node.previousSibling
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
sibling = sibling.previousSibling;
} while(sibling);
if(count == 1) {count = null;}
} else if(node.nextSibling) {
var sibling = node.nextSibling;
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
var count = 1;
sibling = null;
} else {
var count = null;
sibling = sibling.previousSibling;
}
} while(sibling);
}
if(node.nodeType == 1) {
path.push(node.nodeName.toLowerCase() + (node.id ? "[#id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
}
return path;
};
</script>
//function to get xpath location and write in textfield in focus
***<script>
$('#iframe').ready(function () {
var selectedtextbox;
$('input[name="myinput"]').focus(function(){selectedtextbox=$(this);});
$('div, p, li, a, href').click(function () {
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
</script>***
<style type="text/css">
<!--
iframe{width:100%;height:400px;}
-->
</style>
</head>
<body>
<!-- ... -->
<input id="iframe_url" name="" type="text" />
<input id="iframe_button" name="" type="button" />
<iframe id="iframe" src="?url=http://kupime.com"></iframe>
<script type="text/javascript">
document.getElementById('iframe_button').onclick = function () {
document.getElementById('iframe').src = '?url=' + document.getElementById('iframe_url').value;
};
</script>
<!-- ... -->
//Textfields for xpath location to write inside them
<input id="" name="myinput" type="text" value="">
<input id="" name="myinput" type="text" value="">
<input id="" name="myinput" type="text" value="">
</body>
</html>
***
$('#iframe').ready(function () {
var selectedtextbox;
$('input[name="myinput"]').focus(function(){selectedtextbox=$(this);});
$('div, p, li, a, href').click(function () {
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
</script>***
There are 3 issues.
the iframe-element is not accessible at this point(the function is placed above the iframe, the #iframe-element is still unknown)
ready will fire when the current document is ready, not the document within the iframe. Use load instead
you need to set the document within the iframe as context-argument
//wait for ready in the current document to have access to #iframe
$(function()
{
$('#iframe')
//observe the load-event of the iframe-element
.on('load',
function ()
{
//set a default-input to avoid errors
var selectedtextbox=$('input[name="myinput"]:eq(0)');
$('input[name="myinput"]')
.focus(function(){selectedtextbox=$(this);});
//Note the 2nd argument here,
//it sets the contextof $() to the document inside the iframe
$('div, p, li, a, href',
this.contentWindow.document)
.click(function ()
{
var xpath = getXPath(this);
selectedtextbox.val(xpath)
});
});
});

Categories