uploadify not uploading images using php - php

I want to use uploadify to upload my multiple images.
What is scenario
I want to upload multiple images. I also want to enter the information of each uploaded image in database as well. As at `oncomplete event I want to get the ids of all newly entered ids of table
What I have done
my uploadify code
$(document).ready(function() {
$('#fileid').uploadify({
'uploader' : '<?php echo SITEURL;?>/admin/uploadify/uploadify.swf',
'script' : '<?php echo SITEURL;?>/admin/action_files/area_pics_upload.php',
'cancelImg' : '<?php echo SITEURL;?>/admin/uploadify/cancel.png',
//'folder' : '<?php echo SITEURL;?>/admin/uploadify/uploads',
'auto': 'true',
'fileExt' : '*.jpeg;*.jpg;*.gif;*.png',
'fileDesc' : 'Image Files (*.JPEG,*.JPG, *.GIF, *.PNG)',
'multi' : true,
'onAllComplete': function(event, data)
{ alert(data); }
});
});
Code in area_upload_pics.php
if (!empty($_FILES))
{
$allowedExtensions = array("jpeg","jpg","gif","png");
for($i=0;$i<count($_FILES);$i++)
{
if(in_array(end(explode(".",strtolower($_FILES['fileid'][$i]['name']))),$allowedExtensions))
{
$file = time().'-'.$_FILES["fileid"][$i]['name'];
if(move_uploaded_file($_FILES["fileid"][$i]["tmp_name"],'../../uploaded_files/area_pics/'.$file)
{
//save file info in database
$q = "INSERT INTO ".DB_PREFIX."_files (file) values (".$file.")";
mysql_query($q);
$images_ids[]=mysql_insert_id();
}
}
}
}
echo(json_encde($images_ids);
My Problem
Images are not being uploaded. I haved checked the paths that are good. What amI doing wrong.

I was having wrong concept about uploadify. I was thinking that it hits single time to uploading resource(file doing uploading) so we have to have $_FILES as array.
But the uploadify hits the uploading script as many times as you have selected the files to upload. For example you have selected 6 files to upload. Uploadify will hit your uploading script stated in script property of uploadify 6 times. So you don't need to use for loop and iterate through $_FILES. Just use the script as you use for single file uploading.
This is for those having same problem. :-)

Related

Quick suggestion on php multiple file uploading

I'm using thid code this basically helping me getting file which user drops on browser and then post it to php and echoing file name but the problem is with the array in php when ever i drop 2 files and call the php file and try to echo the count of files it gives me 5 always and it echos the 2 file names and + othes as undefined index.... and if i upload 5 files it show all 5 with no problem....plz help me why this is happing...
Here is my jquery code:
function handleFiles(droppedFiles) {
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) {
// checks if any files were dropped
for(var f = 0; f < droppedFiles.length; f++) {
// for-loop for each file dropped
alert(droppedFiles[f]['name']);
uploadFormData.append("files[]",droppedFiles[f]);
// adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "try.php?size="+s, // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
return false;
}
Here is my php code :
if(isset($_FILES["files"])) {
for ($i=0;$i<count($_FILES['files']);$i++) {
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
It doesn't work this way. $_FILES is an associative array containing the uploaded files, indexed by the field name. Each entry has exactly five elements: name,tmp_name,size,type and error. Each of these elements is an array containing as many elements as the uploaded files.
So if you count($_FILES['files']), the result will always be 5. But if you count($_FILES['files'][$xyz]) where $xyz is any of the above keys, that will be the number of uploaded files.
So your code would work like this, for example:
if(isset($_FILES["files"]))
{
for ($i=0;$i<count($_FILES['files']['name']);$i++)
{
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
or better yet (for readability, if nothing else):
if(isset($_FILES["files"]))
{
$filenames=$_FILES['files']['name'];
for ($i=0;$i<count($filenames);$i++)
{
echo $filenames[$i];
echo "\n";
}
}

Drag and Drop Jquery upload to PHP

I have seen many topics about this problem but none of them got a legit answer or a including PHP file.
I want to make a drag & drop saving tool. The problem is that my files are not getting uploaded to my ftp folder.
I got the following code:
HTML:
<div id="drop_zone">
<p>Drop Here</p>
</div>
<form enctype="multipart/form-data" id="yourregularuploadformId">
<input type="file" name="files[]" multiple="multiple">
</form>
JS:
$(function() {
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
etc.... dropping part
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
files = evt.dataTransfer.files;
uploadFile(files);
etc... getting file to my method
function uploadFile(droppedFiles){
// add your files to the regular upload form
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) { // checks if any files were dropped
for(f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
uploadFormData.append("files[]",droppedFiles[f]); // adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "php/uploadFile.php", // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
}
Got the above code from another topic. (alert(uploadFormData); -> gives me a Formdata aboject)
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"],
"ftp/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
Can't make it work :<
The message i get from the callback function in my JS is:
Undefined index: file
Your PHP code needs to iterate over all of the files in the request. Based on your javascript, your PHP code should look something like this:
foreach ($_FILES["files"] as $file) {
move_uploaded_file($file['tmp_name'], $target);
}
The $target variable must point at the local destination for your file. See the PHP manual for more details.

uploadify - show uploaded images on page

I'm building a site (in php) that uses uploadify to allow a user to upload portfolio images.
I have uploadify working fine, but I'm just wondering the best way of showing the uploaded images on the page once they have been uploaded. Is it possible to do without a page refresh?
I've pasted my uploadify code below:
<script>
<?php $timestamp = time();?>
var counter = 1;
$(function() {
$('#file_upload').uploadifive({
onUploadComplete: function(event, queueID, fileObj, reponse, data) {
//alert(counter);
counter = counter +1 ;
},
'buttonText' : 'Upload Images...',
'uploadLimit' : 12,
'uploadScript' : '/includes/uploadifive.php',
'checkScript' : '/includes/check-exists.php',
'auto' : true,
'method' : 'post',
formData : {
'page_id' : '<? echo $pageDetails->row['page_id'] ?>',
'counter' : counter,
'timestamp' : '<? echo $timestamp;?>',
'token' : '<? echo md5('unique_salt' . $timestamp);?>'
},
});
});
</script>
I'm not too sure how to get the file name from uploadify
Sure, you can just add img elements to the page dynamically via the DOM:
var img = document.createElement('img');
img.src = "/path/to/the/new/img.png";
document.getElementById("somecontainer").appendChild(img);
Live Example | Source
You may need to do an ajax call to the server to get the path of the new image, unless that falls out naturally from your application logic.
In the edition I use there is a function
onUploadSuccess : function(file,data,response){
}
Then I can get file name by file.name;
So in your code maybe the fileObj, You can try fileObj.name to get the name of the file you upload.

uploadify session problem

Hello I'm using Uploadify to upload photos.
When user is logged, his ID is stored in session, but after uploading anything by Uploadify, his ID is deleted from session, so it looks like he is not logged in.
I tried to pass his ID with session ID and session name as scriptData, but it did not work either. When user is logged in and tries to upload sth, after upload session is clean (there is no user ID and uploaded photo name stored).
When the user is not logged in, session contains uploaded photo name...
Here is the .js:
$(document).ready(function() {
$('#fileUpload').uploadify({
'uploader' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/uploadify.swf',
'script' : '{/literal}{$URL_PREFIX}{$tc->get('uploadify')}{literal}',
'scriptData' : {'PHP_SESS_ID': '{/literal}{$sessionId}{literal}','PHP_SESS_NAME':'{/literal}{$sessionName}{literal}'{/literal}{if $user},'PHP_SESS_UZIV':'{$user->get('Id')}'{/if}{literal}},
'cancelImg' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/cancel.png',
'fileDataName' : 'Filedata',
'fileExt' : '*.jpg;*.gif;*.png',
'fileDesc' : 'Image Files',
'sizeLimit' : 5242880, // 5x1024x1024 bytes
'auto' : false,
'buttonText' : 'VYBERTE FOTKU',
'buttonImg' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/uploadify-butt-{/literal}{$lang}{literal}.jpg',
'rollover' : true,
'width' : 300,
'height' : 45,
'hideButton' : false,
'method' : 'post',
'multi' : false,
'onAllComplete' : function(event,data) {
window.location.href = '{/literal}{$URL_PREFIX}{$tc->get('photo-uploaded')}{literal}';
}
});
});
Here is the backend script:
if (!empty($_FILES)) {
$session_id = $_POST["PHP_SESS_ID"];
$session_name = $_POST["PHP_SESS_NAME"];
session_id($session_id);
session_name($session_name);
if (isset($_POST["PHP_SESS_UZIV"])) {
$user_id = $_POST["PHP_SESS_UZIV"];
$_SESSION['sess_us_id'] = $user_id;
}
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = dirname(dirname(__FILE__)) . '/img/';
$newName = time() . '_' . StripAccent($_FILES['Filedata']['name'], '', false, false);
$targetFile = str_replace('//','/',$targetPath) . $newName;
$savePic = savePic($targetPath, $newName, -590, -500, 100, $tempFile);
$saveThumb = savePic($targetPath, getThumbName($newName), -185, -142, 100, $targetFile);
$_SESSION['uploadedPhoto'] = $newName;
}
Thanks for help
EDIT: Well I've found out this code works on one, but not the other server...
This worked for me:
in your code which display file upload button:
<?php
session_start();
?>
....
$(function() {
$('#file_upload').uploadify({
'formData' : {
'PHPSESSID': '<?=session_id()?>'
},
'buttonText' : 'Upload',
'displayData': 'speed',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
'onUploadSuccess' : function(file, data, response) {
....
}
});
});
and on uploadify.php
just do this:
session_id($_POST['PHPSESSID']);
session_start();
and that's it, all session data will be accessible in uploadify.php.
Works for me.
Hope I helped someone.
What exactly are you using to generate this Javascript?
'scriptData' : {'PHP_SESS_ID': '{/literal}{$sessionId}{literal}','PHP_SESS_NAME':'{/literal}{$sessionName}{literal}'{/literal}{if $user},'PHP_SESS_UZIV':'{$user->get('Id')}'{/if}{literal}},
Is this being echoed out from PHP? Where is $sessionID, $user, $PATH_TO_ROOT etc... being defined?
Is there a session_start() executed somewhere before your sample upload handling code starts up? Without that, all your session manipulation will be gone when the script exits. You must call session_start() for PHP to preserve $_SESSSION for you.
Make sure that Uploadify is actually getting the proper session names/ID - if it's getting them wrong, then your code will reset the session id/name to something other than what the real session is, and you'll end up with the symptoms you have - vanishing upload data - because it went into some OTHER session.
As well, you don't seem to have ANY error handling in your script and assume the upload succeeded. At bare minimum you should have:
if ($_FILES['Filedata']['error'] === UPLOAD_ERR_OK) {
... process upload ...
} else {
die("Upload failed with error code #" . $_FILES['Filedata']['error']);
}
Just because the _FILES array isn't empty doesn't mean an upload succeeded. PHP will still fill in as much information as it can about the upload, INCLUDING the error code, which means there will ALWAYS be data in that array, regardless of the upload's success/failure.
Do you happen to be testing this with Internet Explorer?
http://www.uploadify.com/documentation/uploadify/using-sessions-with-uploadify/
$('#file_upload).uploadify({
// Your normal options here
formData : { '<?php echo session_name();?>' : '<?php echo session_id();?>' }
});
In Uploadify:
//uploadify.php
$session_name = session_name();
if (!isset($_POST[$session_name])) {
exit;
} else {
session_id($_POST[$session_name]);
session_start();
}

problem with returning the filename using Uploadify

I am using the Uploadify Plugin to upload the picture, and i am doing some operations like
a) when a user upload the file the upload button is removed automatically
b) and the uploadify.php script will rename the file and store it in designated directory.
and here is the code which i am using to perform the action.
Jquery Code :
<script type="text/javascript">
$(document).ready(function() {
$('#fileUpload, #fileUpload2').uploadify({
'uploader': 'img/uploadify.swf',
'script': 'uploadify.php',
'folder': 'upload',
'auto' : 'true',
'cancelImg': 'img/cancel.png',
'fileDesc': 'jpg/jpeg',
'displayData': 'percentage',
'fileExt': "*.jpg;*.jpeg",
'sizeLimit' : '8388608',
'fileDataName' : 'file',
onComplete : function(event, queueID, fileObj, reposnse, data)
{
$('#filesUploaded').append('<a href='+fileObj.filePath+'>'+fileObj.name+'</a><br>');
$("#firstUpload").remove();
}
}); });
</script>
and in the php i have used the combination of date with a unique id to rename the file which is perfectly working fine.
but when i want to view the file name and i do that by calling the div
<div id="filesUploaded"></div>
it shows the original filename and not the renamed file. i tried changing the value from '+fileObj.name+' to '+response+'
i guess the problem is within the above code as the file.Obj.name prints the selected file name and not the processed file, and when i change it to +response+ it uploads the file and rename it but in the form page it does not print the renamed file name. and it freezes with the progress bar composing 100% progress.
how do i make it print the renamed file name.?
thank you
Edit : here is my PHP code .
<?php
include('database.php');
$date = date("dFY");
$query = "SELECT MAX(id) as max_id FROM news";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$max_id = $row['max_id']+1;
echo $max_id;
$file1 = "file_$date"."_$max_id.jpg";
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = 'upload/';
move_uploaded_file($tempFile,$targetPath.$file1);
}
?>
For me this didn't work. I was looking for something similar - this is what worked for me:
'onUploadSuccess' : function(file, data, response) {
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
}
In my case I used my uploadify.php to create a unique filename - then I used echo $filename - rather than '1'. That way "data" always contains the newest filename.
Cheers
Here's the problem. The Javascript code has a typo. You have written reposnse instead of response in onComplete call. Do it like this:
onComplete : function(event, queueID, fileObj, response, data)
Then when you do the +response+, the script will not hang and will show the MaxID (which you're outputing from the PHP script).

Categories