Question

I'm using uploadify, and i can't set sessions in my php files, my script looks like this:

    $("#uploadify").uploadify({
        'uploader'       : '/extra/flash/uploadify.swf',
        'script'         : '/admin/uploads/artistsphotos',
        'scriptData'     : {'PHPSESSID' : '<?= session_id(); ?>'},
        'cancelImg'      : '/images/cancel.png',
        'folder'         : '/img/artists',
        'queueID'        : 'fileQueue',
        'auto'           : false,
        'multi'          : true,
        'onComplete'     : function(a, b, c, d, e){

        },  
        'onAllComplete': function(event,data){
            $bla = $('#art').find(':selected',this);
            $fi  = $bla.val();
             $.ajax({
               type: "POST",
               url: "/admin/uploads/artistsphotosupload",
               data: "artist="+$fi,
               success: function(msg){
                 console.log(msg);
               }
             });
     }
});

And in php if i try:

$_SESSION['name'] = 'something';

I can't access it in another file.and i have session_start(); activated Any solutions?

Was it helpful?

Solution

Usually the session ID won't be read from POST. You could do this:

$_COOKIE['PHPSESSID'] = $_POST['PHPSESSID'];
session_start();

OTHER TIPS

you cannot solve this because uploadify has own session ID which is created by flash player. In other words the flash player access the uploadify script as a new user and gets a new session. The only way you can solve this is to pass current page session_id through post to the uploadify script.

I found a solution which is far easier to implement, especially if you already have a session-oriented PHP backend for login, etc.:

just write the following code in the jQuery statement:

'script'    : '/upload.php?<?= session_name(); ?>=<?= session_id(); ?>',

which will magically attach your current session name and your session id.

This may work but from a security perspective is really bad practice. This would allow anyone with a valid sessionID to impersonate that session just by changing the sessionid. It would be better to do even a basic synchronous encryption of the sessionid with a secret key (known only to the backend code), and then decrypt it on the upload.php script.

I'm currently having a similar problem with uploadify + PHP sessions.

Using error_log() I can monitor that when the uploadify flash app sends the file data up to the server, it passes the correct session_id to the upload script:

'scriptData' : { 'session_id' : session_id },

(session_id set earlier: var session_id = '';)

So, that lets me check that yes, the session id for my pages and the session id for the uploadify script are in fact the same.

But, when the script runs and I start the session by:

session_id($session_id); session_start();

Somehow ALL the session data is destroyed (I've also been setting session data into an array so I can refresh and watch the data grow with each request, then when I use uploadify, it's wiped).

I have no clue on how to debug this :/

edit: suhosin may be destroying the session:

http://www.uploadify.com/forum/viewtopic.php?f=7&t=2062

Add this before your external .js file with the uploadify implementation.

<!-- Get sesssionId -->
 <script type="text/javascript" charset="utf-8">
  var sessionId = "<?php echo session_id(); ?>";
 </script>

Then add this to the uploadify script.

$('#uploadify').uploadifySettings('scriptData', {'sessionId': sessionId});

PHP upload script needs this.

// Start session
 session_id($_POST['sessionId']);
 session_start();

All done!

After reading all the brilliant replies regarding both security and method, I've worked my own way around the problem, and I'll post it here for the benefit of others. Skip to the bottom for the solution, it's all that matters right? ;).

Uploadify uses it's own default session...

This is an annoyance that means that when accessing uploadify.php, any session variables you had previously stored can't be accessed from the current (uploadify) session. You're essentially looking at a session object that is completely unrelated to the session you made. Aaah, so what do we do, pass it through the javascript?

You "can" pass a reference to the session through javascript, but javascript is client (user) side, and because of this, a user can change the session reference before it is sent off to the server. He could effectively fake his session ID. This is actually terrifyingly dangerous, at least in the case of my application.

The solution...

Do NOT use the default session_start() on it's own, which AFAIK can not be referenced by an ID. Instead, every time you use session_start(), set an ID for the session you wish to use, (which I now feel is good practice regardless).

EVERY SINGLE TIME you wish to start a session

session_id("IDHere");

session_start();

IMPORTANT: Setting a unique session for each user.

Sessions are variables shared between the server and every other client connecting with reckless abandon. If you want to store session variables that are unique to each individual user of your site, the session_id HAS to be some sort of completely unique dynamic ID relative to that user. This can be accessed from a cookie, or more securely a database (the user's unique ID?).

Edit: After a bit of research, it seems that default sessions (without an ID) use the sessionID "PHPSESSID". So although I haven't tried it yet, setting session_id("PHPSESSID"), before you start the session in uploadify.php may fix the problem too.

But still, if a plugin just so happens to use an identical session variable to you inside the same session, problems could spring up, so it's probably best to make your session with it's own unique ID anyway.

put a label hide in the document with id = "id_usuario_logueado" and value $_SESSION[id]

just write the following code in the jQuery statement:

'scriptData': {'id_usuario':$('#id_usuario_logueado').text()},

later in php

$id_usuario = $_POST['id_usuario'];

I found the solution, if your backend script needs authentication and redirects you will get the 302 problem - simply create a new controller or script that does not need authentication.

Then, from the code above change 'script' : '/admin/uploads/artistsphotos', To 'script' : '/admin/uploads-unprotected/artistsphotos/id=< ?php echo md5($theUserSessionId); ?>',

Then in your backend script simply check the id that was passed and authenticate the upload request with a different strategy.

Here is the answer directly from uploadify: Using Sessions with Uploadify

In your .php that calls the ajax:

'scriptData': {'<?php echo session_name();?>':'<?php echo session_id();?>'},

And in your uploadify.php (receiving/saving program)

$session_name = session_name();

if (!isset($_GET[$session_name])) {
    exit;
} else {
    session_id($_GET[$session_name]);
    session_start();
}

I am using 2.1.4, and it works like a charm for session variables.

$(document).ready(function() {



nombre = $('#uploadify1').val(); //first input

autor = $('#uploadify1').val();   // second one



$("#uploadify").uploadify({

    'uploader'       : UPLOADIFY_URL+'scripts/uploadify.swf',

    'script'         : 'ticket_docs_uploadify.php',

    'cancelImg'      : UPLOADIFY_URL+'cancel.png',

    'folder'         : 'ticket_document_uploads',

    'queueID'        : 'fileQueue',

    'checkScript'    : 'ticket_docs_check.php?nombre='+nombre+'&autor='+autor,

    'fileDesc'       : 'I am testing uploadify',

    'buttonText'     : 'Upload',

    'scriptData'     : {'sessTempTickedId': '<?php echo $_SESSION['sessTempTickedId'];?>', 'pkEmployeeID': '<?php echo $_SESSION['pkEmployeeID'];?>', 'EmployeeDepartment': '<?php echo $_SESSION['EmployeeDepartment'];?>' },

    'auto'           : false,

    'multi'          : true,        

    'onComplete'     : function(a, b, c, d, e){

        //alert(a+b+c+d+e);

    },

    'onAllComplete': function(event,data){

        //something here             alert('asdasd');             alert(json_decode(data));            

    }

});

});



<?php include_once('../../common/inc/connectdb.inc.php');

if (!empty($_FILES))

{

$tempFile = $_FILES['Filedata']['tmp_name'];

$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';

//change the file name here



$fileName = time();



$arrFile = pathinfo($_FILES['Filedata']['name']);



$strFileExt = strtolower($arrFile['extension']);



$strFileName = $arrFile['filename'];



$strFileBaseName = $arrFile['basename'];



$fileName = $fileName.'.'.$strFileExt;



$targetFile = str_replace('//','/',$targetPath) . $fileName;



$sql = "INSERT INTO ticket_documents (fkTicketID,fkEmployeeID,fkDepartmentID,TicketDocumentName,TicketDocumentLabel) VALUES ('".$_POST['sessTempTickedId']."','".$_POST['pkEmployeeID']."','".$_POST['EmployeeDepartment']."','".$fileName."','".$_FILES['Filedata']['name']."')";

mysql_query($sql) or die(mysql_error());



move_uploaded_file($tempFile,$targetFile);

echo "1";

}

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top