Pytrin, question swfupload solved

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
scarface222
Forum Contributor
Posts: 354
Joined: Thu Mar 26, 2009 8:16 pm

Pytrin, question swfupload solved

Post by scarface222 »

Hey I know you said you have used this application so I just have some quick questions, then this problem should be solved basically. The scripts are a little confusing and new to me. I got the progress working however I am just a little confused with how the application communicates with php. When I submitted the form without swfupload I would get error messages when the file was incorrect from my file validator upload.php. I just have two quick concerns where I am having trouble finding the answer. If you still remember any of your last projects pytrin, I would really appreciate some pointers.

1. Do I need a session_id for the upload to work? How is it involved with my upload.php? I already started a session on all my pages to deal with user logins so will starting a session on the upload.php will that interfere?

2. How do you pass the file information to your upload.php? I assume it is through the post_params but it does not seem to be working since the file progress is shown but the upload does not go through to upload.php since there are no errors and the file is not saved.

See my scripts if you need to, to give you an idea of what I tried to do

This is my initializer (see post_params)

Code: Select all

<script type="text/javascript">
var swfu;
 
SWFUpload.onload = function () {
    var settings = {
        flash_url : "../progressbar/swfupload/swfupload.swf",
        upload_url: "../progressbar/upload.php",
        post_params: {
            "PHPSESSID" : "<?php echo session_id(); ?>",
            "Filedata" : "Filedata",
            "#username" : "username",
            "#selection" : "selection"
        },
        file_size_limit : "100 MB",
        file_types : "*.*",
        file_types_description : "All Files",
        file_upload_limit : 100,
        file_queue_limit : 0,
        custom_settings : {
            progressTarget : "fsUploadProgress",
            cancelButtonId : "btnCancel"
        },
        debug: false,
 
        // Button Settings
        button_image_url : "../progressbar/swfupload/XPButtonUploadText_61x22.png",
        button_placeholder_id : "spanButtonPlaceholder",
        button_width: 61,
        button_height: 22,
 
        // The event handler functions are defined in handlers.js
        swfupload_loaded_handler : swfUploadLoaded,
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        queue_complete_handler : queueComplete, // Queue plugin event
        
        // SWFObject settings
        minimum_flash_version : "9.0.28",
        swfupload_pre_load_handler : swfUploadPreLoad,
        swfupload_load_failed_handler : swfUploadLoadFailed
    };
 
    swfu = new SWFUpload(settings);
}
 
</script>
These are 3 of my form inputs which I tried to use in post_params

Code: Select all

 
<input type="hidden" name="username" id="username" value="<?php echo $session->username; ?>" />
 
<span id="spanButtonPlaceholder"></span>
 
  <select name="selection" id="selection">
<option value="1">Chat Image</option>
<option value="2">MP3</option>
<option value="3">Change User Image</option>
</select>
This is a sample of my upload.php

Code: Select all

if($_POST["selection"]==3){
    
    $username=$_POST["username"];
 
# edit #
    $maxwidth = 1024;
    $maxheight = 1024;
    $max_filesize = 1024000;
 
    $uploads = "../usercontent/$username/images";
    $types_array = array('image/gif','image/jpeg','image/x-png', 'image/jpg');
# end edit #
 
if($_FILES['Filedata']['name'] == "")
{
      echo"<script>
alert(\"Please select a file to upload!\");
</script>";
return;
}
 
 
if (!getimagesize($_FILES['Filedata']['tmp_name'])){
         echo"<script>
alert(\"That file type is not allowed!\");
</script>";
return;
}
 
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".js", ".shtml", ".pl" ,".py");
foreach ($blacklist as $item) {
if(preg_match("/$item\$/i", $_FILES['Filedata']['name'])) {
echo "We do not allow uploading of this type of file\n";
     echo"<script>
alert(\"We do not allow uploading of this type of file. Your account has been flagged!\");
</script>";
return;
}
}
 
    $max_filesize_kb = ($max_filesize / 1024);
 
if($_FILES['Filedata']['size'] > $max_filesize_kb)
{
     echo"<script>
alert(\"Your file is too large it must be.$max_filesize_kb\");
</script>";
return;
}
 
    $imagesize = getimagesize($_FILES['Filedata']['tmp_name']);
 
    $imagewidth = $imagesize[0];
    $imageheight = $imagesize[1];
 
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
     echo"<script>
alert(\"The resolution is too large files may be up to ".$maxwidth."px x ".$maxheight."px in size\n\");
</script>";
}
/*check for image*/
 
$checkimage="SELECT * FROM images WHERE username='$username'";
    $queryimage=mysql_query($checkimage) or die('Error, select query failed');
while ($row = mysql_fetch_assoc($queryimage)) {
    $image=$row['image'];
}
 
    $myFile = "../usercontent/$username/images/$image";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
unlink($myFile);
 
 
/*insert into database*/
$image1=urlencode($_FILES['Filedata']['name']);
$second_query = "UPDATE images SET image='$image1'
WHERE username='$username'";
mysql_query($second_query) or die('Error, insert query failed');
 
/*copy file*/
move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploads.'/'.urlencode($_FILES['file']['name']))
or die ("Couldn't upload ".$_FILES['Filedata']['name']."\n");
 
 
 echo"<script>
alert(\"File uploaded Refresh the page to view it\");
</script>";
return;
 
}
Last edited by scarface222 on Sun Jan 17, 2010 12:18 am, edited 1 time in total.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Pytrin, question swfupload

Post by Eran »

The file upload is a separate operation from the form submission, as its handled by flash via swfupload. In your code you attempt to handle both in the same script, while you should have a separate script handling the flash file upload. The entire interaction happens through flash which you can control via Javascript handles. You have a plethora of different events that you can use for each part of the file-upload process - http://demo.swfupload.org/Documentation/#events
You can use those events to debug your code (especially the uploadError and uploadComplete events).

A common approach to using an asynchronous file-upload such as this is to store the uploaded file in a temporary location and return the file name to original form. After form submission you just move the previously uploaded file from the temporary location to a permanent one (a simple file move, as it's already been uploaded).

Regarding sessions, you only need to pass the session_id if you need the session for the file upload (for example, if you need a logged-in user details). If so, you need to send the session_id with the file upload request and load it manually through PHP as flash does not preserve the original session in Firefox for some reason.
scarface222
Forum Contributor
Posts: 354
Joined: Thu Mar 26, 2009 8:16 pm

Re: Pytrin, question swfupload

Post by scarface222 »

I was actually using a file called handlers.js shown below and another called fileprogress.js to handle progress to test this thing out but they do not attempt to move a file to a temp directory. So you are saying that file validation happens in flash? I need to upload to a temporary directory and then move the file with php? Is it possible to do file validation checks like the script I showed you with php while using swfupload or can I only move the file with php? I found this which shows a php validation to use with swf upload but it does not show the javascript so I am not sure how to post the file to a script like this http://atutorsvn.atrc.utoronto.ca/repos ... upload.php

or send error messages back, although it shows
header("HTTP/1.1 500 Internal Server Error");
echo "POST exceeded maximum allowed size.";

which I assume is a way of communicating with the swfupload script



handlers.js

Code: Select all

 
function swfUploadPreLoad() {
    var self = this;
    var loading = function () {
        //document.getElementById("divSWFUploadUI").style.display = "none";
        document.getElementById("divLoadingContent").style.display = "";
 
        var longLoad = function () {
            document.getElementById("divLoadingContent").style.display = "none";
            document.getElementById("divLongLoading").style.display = "";
        };
        this.customSettings.loadingTimeout = setTimeout(function () {
                longLoad.call(self)
            },
            15 * 1000
        );
    };
    
    this.customSettings.loadingTimeout = setTimeout(function () {
            loading.call(self);
        },
        1*1000
    );
}
function swfUploadLoaded() {
    var self = this;
    clearTimeout(this.customSettings.loadingTimeout);
    //document.getElementById("divSWFUploadUI").style.visibility = "visible";
    //document.getElementById("divSWFUploadUI").style.display = "block";
    document.getElementById("divLoadingContent").style.display = "none";
    document.getElementById("divLongLoading").style.display = "none";
    document.getElementById("divAlternateContent").style.display = "none";
    
    //document.getElementById("btnBrowse").onclick = function () { self.selectFiles(); };
    document.getElementById("btnCancel").onclick = function () { self.cancelQueue(); };
}
   
function swfUploadLoadFailed() {
    clearTimeout(this.customSettings.loadingTimeout);
    //document.getElementById("divSWFUploadUI").style.display = "none";
    document.getElementById("divLoadingContent").style.display = "none";
    document.getElementById("divLongLoading").style.display = "none";
    document.getElementById("divAlternateContent").style.display = "";
}
   
   
function fileQueued(file) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("Pending...");
        progress.toggleCancel(true, this);
 
    } catch (ex) {
        this.debug(ex);
    }
 
}
 
function fileQueueError(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
            return;
        }
 
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);
 
        switch (errorCode) {
        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            progress.setStatus("File is too big.");
            this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            progress.setStatus("Cannot upload Zero Byte files.");
            this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            progress.setStatus("Invalid File Type.");
            this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        default:
            if (file !== null) {
                progress.setStatus("Unhandled Error");
            }
            this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}
 
function fileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        if (numFilesSelected > 0) {
            document.getElementById(this.customSettings.cancelButtonId).disabled = false;
        }
        
        /* I want auto start the upload and I can do that here */
        this.startUpload();
    } catch (ex)  {
        this.debug(ex);
    }
}
 
function uploadStart(file) {
    try {
        /* I don't want to do any file validation or anything,  I'll just update the UI and
        return true to indicate that the upload should start.
        It's important to update the UI here because in Linux no uploadProgress events are called. The best
        we can do is say we are uploading.
         */
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("Uploading...");
        progress.toggleCancel(true, this);
    }
    catch (ex) {}
    
    return true;
}
 
function uploadProgress(file, bytesLoaded, bytesTotal) {
    try {
        var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
 
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setProgress(percent);
        progress.setStatus("Uploading...");
    } catch (ex) {
        this.debug(ex);
    }
}
 
function uploadSuccess(file, serverData) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);
 
    } catch (ex) {
        this.debug(ex);
    }
}
 
function uploadError(file, errorCode, message) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);
 
        switch (errorCode) {
        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
            progress.setStatus("Upload Error: " + message);
            this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
            progress.setStatus("Upload Failed.");
            this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
            progress.setStatus("Server (IO) Error");
            this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
            progress.setStatus("Security Error");
            this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            progress.setStatus("Upload limit exceeded.");
            this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
            progress.setStatus("Failed Validation.  Upload skipped.");
            this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            // If there aren't any files left (they were all cancelled) disable the cancel button
            if (this.getStats().files_queued === 0) {
                document.getElementById(this.customSettings.cancelButtonId).disabled = true;
            }
            progress.setStatus("Cancelled");
            progress.setCancelled();
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
            progress.setStatus("Stopped");
            break;
        default:
            progress.setStatus("Unhandled Error: " + errorCode);
            this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}
 
function uploadComplete(file) {
    if (this.getStats().files_queued === 0) {
        document.getElementById(this.customSettings.cancelButtonId).disabled = true;
    }
}
 
// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
    var status = document.getElementById("divStatus");
    status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}
 
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Pytrin, question swfupload

Post by Eran »

So you are saying that file validation happens in flash?
No, I don't recall saying that.
I need to upload to a temporary directory and then move the file with php?
You upload it through flash to a separate PHP script first. You store the results in a hidden field on your form. After the form submission you use move the file from the temporary location to a permanent one. The reason for this being that since the file is uploaded separately from the form, there is not guarantee that the form would ever be successfully submitted (as opposed to a normal file upload where you can test that first). After a successful form submission you move the file to a permanent location, the same as you would if you were uploading a file normally.
header("HTTP/1.1 500 Internal Server Error");
echo "POST exceeded maximum allowed size.";
What is this? it looks like PHP code. Is this the error it's showing? seems unlikely to show PHP code as an error message
scarface222
Forum Contributor
Posts: 354
Joined: Thu Mar 26, 2009 8:16 pm

Re: Pytrin, question swfupload

Post by scarface222 »

Ok that seems a little more clear to me now, the header php code is from here,

http://atutorsvn.atrc.utoronto.ca/repos ... upload.php

I found this script which I just used as an example to illustrate my question of how to use php with the swf javascript scripts.

Thanks for your time man I will just read through the manual and try to figure this out.

one more question, post_params, do I need to use it for $_POST variables to be defined in my validation.php doc?

for example

<input type="hidden" name="username" id="username" value="<?php echo $session->username; ?>" />

would i use

"#username" : "username",

in post params?
scarface222
Forum Contributor
Posts: 354
Joined: Thu Mar 26, 2009 8:16 pm

Re: Pytrin, question swfupload

Post by scarface222 »

I figured everything out finally, it was difficult because I have not used this before and do not normally work with much javascript unless it is jquery. Thanks again for your help pytrin.
Post Reply