uploadify session problem - php

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

Related

Uplodify returns HTTP Error 302 in firefox

I am using uplodify to upload files to my server.
It is working with no issue in Google Chrome. But when I try to upload a file using Firefox I get HTTP Error 302 and the file does not uploaded.
Here is my script
<?php $timestamp = time();?>
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5($timestamp);?>',
'session' : '<?php echo $session->currentSessionID(); ?>',
'upload_path': 'ticketing_center/',
'allowed_extentions': 'jpg,jpeg,gif,PNG,JPG,png,JPEG,pdf,jpeg,zip,rar,doc,docx,csv,xls,xlsx,txt,csv,xml'
},
'auto' : true,
'removeCompleted': true,
'swf' : '../../includes/uploadify.swf',
'onError' : function(event, queueID, fileObj, errorObj) { alert(errorObj.type + ' ' + errorObj.info ); },
'uploader' : '../../includes/uploadify.php',
'fileSizeLimit' : '20MB',
'fileTypeExts' : '*.gif; *.jpg; *.JPG; *.png; *.PNG; *.JPEG; *.pdf; *.jpeg; *.zip; *.rar; *.doc; *.docx; *.csv; *.xls; *.xlsx; *.txt; *.csv; *.xml;',
'onUploadSuccess' : function(file, data, response) {
if(response === true){
$('#attached_files').append('<input type="hidden" class="uploadedFiles" name="attachments[]" value="' + $.trim(data) + '" />');
$('#queue_final').append('<div style="display: block;" class="removeFile" id="' + $.trim(data) + '">(x) ' + file.name + '</div>');
} else {
alert('Invalid File Type');
}
$('.removeFile').click( function(){
var file_name = $(this).attr('id');
$( "#dialog-confirm" ).dialog( "open" ).data('file_name', file_name);;
});
}
});
I have done research prior posting this question but none of the solutions that I found solved my problem.
here is what I have tried so far
I have tried adding the session value to the script a 'session' : '<?php echo $session->currentSessionID(); ?>'
Then in my uploadify.php code I did
if (array_key_exists('session', $_REQUEST))
session_id($_REQUEST['session']);
I tried adding header( " HTTP/1.0 200 OK" ); to the top of my PHP script and that did not work as well.
I have tried to add the onError function to display any error but that is not displaying anything.
I am not sure what else could be causing this? Note that it is working on Chrome with no issues.
Here is a screenshot of the error after trying to upload
I am using Firefox 32.0.3.
My Apache is running in Windows Server 2008 R2 I am not sure if this make a difference.
Flash will not pass through your existing PHP Session information, so if you are getting the 302 error it is likely that your application is returning the login URL to the Flash player. To resolve this issue, you could include the session information in scriptData and manage it manually in your application.

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.

How pass and receive formData values in Uploadify?

I have been trying to pass and modify data from the client side of uploadify to the server file uploadify.php using the formData setting. I have tried many of the solutions posted on here and the uploadify forums but with no avail.
Initially both formData values are set to the string 'empty' and then when an upload starts, eAlias is set to 2 and eDate to a date. The server script then receives these values by POST and echos them back to the client script which displays this data in an alert (in onUploadSuccess). In all the possible solutions tried the values are either "" or 'empty', ie the setting on the formData keys in onUploadStart doesn't work.
I have included most of the client script and the server script below.
Any help or advice would be greatly appreciated, thank you.
Client-side script:
<script type="text/javascript">
$(document).ready(function()
{
$(".uploadifyfile").uploadify(
{
'swf' : '/xx/uploadify.swf',
'uploader' : '/xx/uploadify.php',
'auto' : true,
'height' : 15,
'method' : 'POST',
'multi' : false,
'uploadLimit' : 10,
'formData' : { 'eAlias' : 'empty', 'eDate' : 'empty' },
'onUploadSuccess' : function(file, data, response)
{
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ' : ' + data);
document.getElementById("adminForm")[buttonPressed].value = data;
},
'onUploadStart' : function(file)
{
var eventDate = "<?php echo $this->row->dates; ?>";
var eventVenue = 'test';
alert('Venue Alias: ' + eventVenue + '\neventDate: ' + eventDate);
//**** The line below is the one in question ****//
$(".uploadifyfile").uploadify("settings", "formData", {"eAlias": 2, "eDate" : eventDate});
},
'onSelect' : function(event, ID, fileObj)
{
var eid = event.id;
if(eid == "SWFUpload_0_0")
{
window.buttonPressed = "custom01";
alert('1');
}
...
}
});
});
</script>
Server-side script
$targetFolder = '/xx/uploads'; // Relative to the root
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Set $someVar to 'someValue'
$eventAlias = $_POST['eAlias'];
$eventDate = $_POST['eDate'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $targetFolder . '/' . $_FILES['Filedata']['name'];
echo ' eventAlias: '.$eventAlias.' eventDate: '.$eventDate;
} else {
echo 'Invalid file type.';
}
}
The problem was as I thought; it was because I was using multiple instances of the uploadify button and referring to them using the .uploadifyfile class. Uploadify doesn't seem to work fully when using classes.
The, probably rudimentary, solution I came up with was to use the 'onSelect' function to store the id of the button pressed into a global variable (window.uploadid) and then use this in the 'onUploadStart' function. Now, for example, when the 2nd button is pressed, the fileType attribute is changed to finalDetails successfully.
I had looked at using jQuery selectors, but they didn't seem to work in this case for id's, just classes.
I've no doubt that there will be several optimisations do be made to the below code, but I hope it will save anyone who was in the same situation as I was many hours of work.
<script type="text/javascript">
$(document).ready(function()
{
$(".uploadifyfile").uploadify(
{
...
'method' : 'post',
'formData' : { 'eventDate' : 'notSet', 'eventVenue' : 'notSet', 'fileType' : 'notSet' },
'onUploadStart' : function(file)
{
var eventDate = "<?php echo $this->row->dates; ?>";
var eventVenue = "<?php echo JFilterOutput::stringURLSafe($this->row->venue); ?>";
$(uploadid).uploadify('settings','formData',{ 'eventDate' : eventDate, 'eventVenue' : eventVenue, 'fileType' : fileType });
},
'onSelect' : function(event, ID, fileObj)
{
alert('event.id:' + event.id);
var eid = event.id; // To determine which button was pressed
if(eid == "SWFUpload_0_0") // Flyer upload
{
window.buttonPressed = "custom01";
window.uploadid = "#file_upload";
window.fileType = "flyer";
}
else if(eid == "SWFUpload_1_0") // Final Details upload
{
window.buttonPressed = "custom02";
window.uploadid = "#file_upload2";
window.fileType = "finalDetails";
}
...
}
});
});
</script>
...
<input type="file" name="file_upload" id="file_upload" class="uploadifyfile" />
...
<input type="file" name="file_upload2" id="file_upload2" class="uploadifyfile" />
your clientSide code is right.i use the same code ,and it works well.so you'd better use id to generate a uploadify instance instead of class

uploadify not uploading images using 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. :-)

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