How to get Uploadify working with Codeigniter + CSRF? - php

I'm trying to get Uploadify 2.1.4 to work with Codeigniter 2.1.0 and CSRF and I'm not having much luck. I have a very basic upload controller & the following code for uploadify:
$(function() {
var cct = $.cookie('csrf_cookie_name');
$('#uploadifyMe').uploadify({
'uploader' : '<?php echo site_url(); ?>js/uploadify/uploadify.swf',
'script' : '<?php echo site_url(); ?>upload/',
'cancelImg' : '<?php echo site_url(); ?>js/uploadify/cancel.png',
'multi' : true,
'auto' : false,
'fileExt' : '*.jpg;*.jpeg',
'fileDesc' : 'Image Files (JPG, JPEG)',
'fileDataName' : 'imgData',
'queueID' : 'fileQueue',
'simUploadLimit' : 1,
'sizeLimit' : 7340032,
'removeCompleted': false,
'scriptData' : { 'csrf_token_name' : cct, 'upload' : 'true' },
'onSelectOnce' : function(event, data) {
$('.uploadifyProgress').addClass('progress');
$('.uploadifyProgressBar').addClass('bar');
},
'onComplete' : function(e, i, f, r, d) {
console.log(r);
},
'onError' : function(e, i, f, eO) {
console.log(eO);
if(eO.info == 500) {
$('#status').prop('class', 'alert alert-error').html('<a class="close" data-dismiss="alert">×</a><h4>Hmmm. Something gone wrong it has.</h4> Yoda has discovered that your security token has expired. This is because you have been here for longer than two hours. we cannot refresh your key automatically, please refresh the page and try again.');
}
}
});
});
The problem is when I upload an image I get a HTTP 500 thrown back at me. I now know it's due to CSRF being turned on since if I turn it off it works fine.
I've tried a load of solutions to the problem. The one you can see in my code, and a one from here that clones your session data and sends it across with the CSRF key, but nothing works. I always end up with a 500 HTTP unless I turn off CSRF.
If anyone can help it would be really appreciated. I realize this question seems to get asked a lot, and it's driving me nutty. On a side note passing the CSRF along with standard AJAX requests works fine, just not with uploadify.

Use this code, it enables you to define an array of controller methods that are not subject to CSRF: https://github.com/EllisLab/CodeIgniter/pull/236.

The issue is that Uploadify uses a Flash object, which is like a completely different browser, with different session, so the CSRF won't match your session if you POST the cookie data.
You would need to override the original CSRF function with a MY_Security.php file and make so you can get around it by, in example, sending your entire session cookie via POST and make so the CSRF can read it, so you can be matched.
You might as well try HTML5 uploaders like https://github.com/blueimp/jQuery-File-Upload that at least gives you a better chance at not having to do such overrides.

Related

Mobile browsers doesn't support session variables?

I have a browser version of my web app and I have some values stored in cookies. Now I am making a mobile version and it seems that my cookies are not working.
Is it possible to use cookies on mobile devices?
I am trying to perform this code and my php is giving me an empty value:
$(document).ready(function() {
var session_lang= '<?php if(isset($_SESSION['SESS_LANGUAGE']))
echo $_SESSION['SESS_LANGUAGE'];?>';
if (session_lang!='')
{
check_and_change(session_lang);
}
});
Is there any other way to store data in internal memory so it can work as cookie?
Does mobile devices support session variables? I am looking on the firebug and I can see that I can create session variable but when I want to read it it is null.
What could be a problem and how to solve this?
EDIT:
I will put you almost entire code so you can see what am I doing...btw. this code is working normally on PC browser.
Javascript file:
$(document).ready(function() {
function languageChange()
{
var lang = $('#websites1 option:selected').val();
return lang;
}
$('#websites1').change(function(e) {
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax({
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response) {
check_and_change(response.message);
}
});
return false;
});
} );
function check_and_change(lang)
{
switch (lang)
{ //do something
}
}
Then this first part that I have put above is on the actual php site that I am looking and which is opening:
And the last thing is pass_value.php:
<?php
session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
I really don't know why this code doesn't work on the mobile phones.
Cookies definitely work on mobile browsers. You say "I am looking on the firebug" which makes me think you aren't really looking at it on a phone.
Have you started the session, and turned on error reporting?
I had a similar situation and discovered that, before my tablet called the script I specified in the URL parameter of the .ajax( ) call, it was actually calling the index.php script again.
Same with my phone. Since I had initialized my session variables in index.php, they kept getting re-set to their initial values (making it look like they were not being correctly stored between pages).
I never figured out why index.php was getting re-called, but I added if !isset( ) checks around the initialization statements and that cleared it up.
On Android, turning on "Data Saver" effectively destroyed my session. I have a login script which will redirect to the previous page when login succeeds. Worked until I turned on Data Saver. Turning it off made it work again. Google does state that Data Saver may affect secure pages which I guess includes my script, which is not on a HTTPS website.

UPLOADIFY loader hangs on 0% when trying to use scriptData

I found a bug while using uploadify. When I user the scriptData attribute to pass post information to the script the loader does not work. The script is actually called and the items are uploaded but the loader hangs on 0 %. When you user multiple files it will hang on the first one sometimes on 95% and mostly on 0%.
It looks as tho the files arent uploaded but they are. This is very anoying though, seeing that the user will think their files arent uploaded and wait on the screen. I tried to work around this by just using GET information and putting my extra variables into the actual url in the script: attribute. This also results in the same problem. A simple note is that I am using CodeIgniter for this project so this could be a problem. It would really be helpful if this was fixed but dont know if its gonna happen any time soon.
I checked this problem on multiple browsers and have the same issue. Has anyone here dealt with this. I used to like uploadify but Im begging to start looking for something else
I had this problem, too, and it drove me crazy. It turns out that the script that you're using to handle the upload has to output something - anything - before uploadify will continue. So in your 'script', like upload.php below, make the last line of the script output something at the bottom of the script - even something simple like echo "done";. This will let uploadify know that the script is finished so it can continue.
$('#file_upload').uploadify({
'uploader' : '/js/jquery/uploadify/uploadify.swf',
'script' : '/distributed/ajax/upload.php',
'cancelImg' : '/js/jquery/uploadify/cancel.png',
'folder' : '/distributed/files',
'auto' : true,
'scriptData': { 'request_no':req_no },
'onComplete': function(evt, ID, fileObj, response, data) {
alert("Finished!");
}
}
});

Uploadify Hanging at random on 100%

I am using Uploadify to enable my users to upload images via my web application.
The problem I am having is that every now and then (at what appears to be random) when the progress bar reaches 100% it 'hangs' and does nothing.
I was wondering if any developers familiar with uploadify may have any idea how to solve this? I am in desperate need of some help.
Here is my front-end code:
<javascript>
jQuery(document).ready(function() {
jQuery("#uploadify").uploadify({
'uploader' : 'javascripts/uploadify.swf',
'script' : 'upload-file2.php',
'cancelImg' : 'css/images/cancel.png',
'folder' : 'uploads/personal_images/' + profileOwner,
'queueID' : 'fileQueue',
'auto' : true,
'multi' : true,
'fileDesc' : 'Image files',
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'sizeLimit' : '2097152',
'onComplete': function(event, queueID, fileObj, response, data)
{
processPersonalImage(fileObj.name);
arrImgNames.push(fileObj.name);
showUploadedImages(true);
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onAllComplete' : function()
{
completionMessage(arrFailedNames);
document.getElementById("displayImageButton").style.display = "inline";
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onCancel' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
},
'onError' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
}
});
});
</javascript>
And server side:
if (!empty($_FILES))
{
//Get user ID from the file path for use later..
$userID = getIdFromFilePath($_REQUEST['folder'], 3);
$row = mysql_fetch_assoc(getRecentAlbum($userID, "photo_album_personal"));
$subFolderName = $row['pk'];
//Prepare target path / file..
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$subFolderName.'/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
//Move uploaded file from temp directory to new folder
move_uploaded_file($tempFile,$targetFile);
//Now add a record to DB to reflect this personal image..
if(file_exists($targetFile))
{
//add photo record to DB
$directFilePath = $_REQUEST['folder'] . '/'.$subFolderName.'/' . $_FILES['Filedata']['name'];
addPersonalPhotoRecordToDb($directFilePath, $row['pk']);
}
echo "1";
die(true);
}
thanks for any help!!
this seems like a php error.
I'd use Fiddler or a similar problem to view the php response or similar.
Check your php error logs, they might shed some light.
I had a similar problem some time ago with Uploadify (using ASP.Net MVC though) - but you will definitely find some useful info regarding the Uploadify event handling and behaviour in the answer posted! Its available here
I had the same problem.
Simply add echo "astlavista babi" to your uploadify script, this echo statement should be the last line, if you have conditional statement then echo should be placed as a last line within the conditional statement.
These are the steps I would take, in order:
1) Be 100% certain you are getting a 200 response from your server. If not, that is the problem
2) Use the latest and the greatest uplaodify and jquery
3) Check for JS errors (firebug console or browser JS debugger will work)
4) Upgrade your Flash player (if that solves it then you can require a higher version)
5) Put a debug statements in the uploadify source, specifically in the complete handler to be sure it gets called
6) If the progress is reaching 100% but the handler never gets called, I'm afraid the next step may be to dive into the actionscript and use the debugger or some trace statements to figure out where the error is. This can mean that there is a bug in calling the external interface function
7) If you make fixes, submit back to uploadify
Chreck your php.ini file for post_max_size parameter. It must be >= upload_max_filesize parameter. For more details see http://php.net/post-max-size.
For future reference: I had this problem when sending data to the upload script using "scriptData" and solved it by simply echoing "ok" in the upload script rather than sending back an empty document.
For those who are using Macs use HTTP Scoop to view the request as Firebug does not show it. More on HTTP Scoop from this blog.

Storing form data in a javascript session

I was wondering if it's possible to store form data such as 'title' and 'description' in a javascript session?
I'm using the uploadify script to have a flash uploader, but the script isn't passing the title and description. This is my code at the moment;
<script type="text/javascript">
jQuery(document).ready(function() {
title = $("input#title").val();
description = $("textarea#description").val();
$('#uploadImage').uploadify({
'uploader': 'flash/uploadify.swf',
'script': 'process/process_uploaded_image.php',
'folder': 'submitted/pictures',
'cancelImg': 'images/cancel.png',
'queueID' : 'fileQueueImages',
'auto' : false,
'multi' : false,
'fileExt' : '*.jpg;*.png;*.gif;*.jpeg;*.JPG',
'fileDesc': 'Images ONLY (.jpg, .png, .gif, .jpeg, .JPG)',
'buttonText' : 'BROWSE',
'scriptData': {'title':title,'description':description,'user':'<?php echo $usr["id"] ?>'},
'sizeLimit' : '2097152', //2MB
//'buttonImg' : '/components/com_mm/assets/images/button-upload-images.png',
//'width' : '218',
//'height' : '66',
onAllComplete: function() {
//$('#uploadedImage').load(location.href+" #uploadedImages>*","");
//location.reload(); //uncomment this line if youw ant to refresh the whole page instead of just the #allfiles div
location.href = "upload-pics-thanks.php";
},
//onComplete: function(a, b, c, d, e){
// if (d !== '1')
// alert(d);
//},
onError: function (a, b, c, d) {
alert("Error: "+d.type+" Info: "+d.info);
},
onSelect: function () {
}
});
});
</script>
Check out this SO answer and in case that doesn't work...
Did you see this post in the Uploadify forums? Maybe it'll point you in the right direction, and wow so much spam in those forums.
http://www.uploadify.com/forum/viewtopic.php?f=7&t=3120
JavaScript does not have sessions. Probably the best way is to send your title&description via AJAX to the server.
If you use latest version of uploadify, the data in scriptData will be passed to script as either _POST or _GET (default is now POST) variable. So in your php file, you can get the title and description using:
$_POST['title']
$_POST['description']
$_POST['user']
Just consider it same with handling form submit, only it's originated from uploadify flash. Also note, the flash is not passing the current cookies that currently exist in the browser. If your php is using session stored in the cookies, it must be tweaked to read it from $_POST instead.
I use CodeIgniter, and there are patch for that in CodeIgniter forum. If you just use build in PHP session, you can pass the PHPSESSID inside scriptData, then in side script PHP, reinitialize session using passed data. It's have been answered in other question in stackoverflow, just search it with uploadify keyword.

Uploadify plugin

Has anyone used this plugin? I don't know if my setup is right, but I think so.
$(document).ready(function () {
$("#uploadify").uploadify({
'uploader': '/extra/flash/uploadify.swf',
'script': '/admin/uploads/artistsphotos',
'checkScript': '/admin/uploads/artistsphotos',
'cancelImg': '/images/cancel.png',
'folder': '/img/artists',
'queueID': 'fileQueue',
'auto': false,
'multi': true,
'onComplete': function (a, b, c, d, e) {
alert(d);
},
'onAllComplete': function (event, data) {
//something here
//alert(data);
}
});
$('.vla').click(function () {
$("#uploadify").uploadifyUpload();
return false;
});
});
If I check with firebug I receive this: http://screencast.com/t/z9PY53bi, but I can't work with the files in PHP,and I also have enctype=".. on the <form>, but when I check the $_FILES array is empty, is my plugin setup wrong?
I have used uploadify before.
Are you using the most recent version of uploadify?
also you shouldn't need a form tag, the 'script' variable is where the uploader sends the file data. Any other information that needs to be sent with it has to be placed in the 'scriptData' variable. Also, I'm not sure if you can send both the script and the checkScript to the same file that might be what is causing the problem.
The script is the file that processes the upload, the checkScript is a script that ensures that the file is not already on the server.

Categories