How to use Uploadify with CakePHP

If you don’t know what uploadify is, it is an excellent script (looks good also by default) that lets you override the default file browser into an input that looks great, is flexible and uses Jquery, Flash and PHP.
It allows you to upload multiple files simultaneously, shows a progress bar and is very easy [...]

If you don’t know what uploadify is, it is an excellent script (looks good also by default) that lets you override the default file browser into an input that looks great, is flexible and uses Jquery, Flash and PHP.

It allows you to upload multiple files simultaneously, shows a progress bar and is very easy to customize.

Using this excellent script into a basic application where you don’t use friendly url’s is piece of cake and you will find many examples on the script’s homepage. However, using it within CakePHP(or any other framework for this matter) may prove a bit tricky.

Here is the best way to do it as i find out…

After you have downloaded the files and extracted the archive, create a layout named upload.ctp in your app/views/layouts/ folder with the following code:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
< html xmlns="http://www.w3.org/1999/xhtml" >
< head >
< meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
< title >< ? echo $title_for_layout; ?>< /title>

< !--JAVASCRIPT-- >

< !--jQuery-- >
< script src="< ?= $html->url("/js/jquery-1.3.2.min.js")?>"       type="text/javascript">< /script>

< script src="< ?=$html->url("/js/jquery.uploadify_source.js")?>" type="text/javascript">< /script>

< !--CSS-->
< link rel="stylesheet" href="url("/css/main.css")?>"         type="text/css" media="screen"/>
< link rel="stylesheet" href="url("/css/uploadify.css")?>"    type="text/css" media="screen"/>
< link rel="stylesheet" href="url("/css/cake.generic.css")?>" type="text/css" media="screen"/>
< /head>
    < body>
        < div id="wrapper">
            < div id="content">
                < ? echo $content_for_layout; ?>
            < /div>
        < /div>
        < ?php echo $cakeDebug; ?>
    < /body>
< /html>

This layout assumes that you have a basic the following files (and locations):

  • /app/webroot/js/jquery-1.3.2.min.js
  • /app/webroot/js/jquery.uploadify_source.js
  • /app/webroot/css/main.css
  • /app/webroot/css/uploadify.css
  • /app/webroot/css/cake.generic.css

Next, create a controller into your application and an action as following :

Class MyControllers extends AppController{

    public function prepare_upload() {

        $this->layout = "upload";

    }
}

This controller will let you to display the uploadify page file selection page.

Create a view with the following contents (these are very important to stick with – try to modify them at your own “risk”):

< script type="text/javascript">
    $(document).ready(function(){
        var path = "url("/app/webroot/uploadify/")?>";
        $('#fileInput').fileUpload({
            'uploader': path + '/uploader.swf',
            'script': path + '/upload.php',
            'folder': path + '/files',
            'cancelImg': path + '/cancel.png',
            'fileExt':"*.leadmesh",
            'fileDesc':"MyExtensions files",
            'auto':true,
            'onComplete': function(event, queueID, fileObj, response, data) {
                window.location = "< ?= $html->url("/MyControllers/process_upload/")?>" + fileObj["name"];
            }
        });
    });
< /script>
< div style="padding:15px">
    < div id="upload_file" style="text-align:center">
        < h3>Upload a ".nice_extension" file to import.< /h3>
        < div align="center">< input height="30" width="110" type="file" name="fileInput" id="fileInput" align="center" />< /div>
    < /div>
< /div>

This view assumes that you have the following files and locations :

  • /app/webroot/uploadify/uploader.swf
  • /app/webroot/uploadify/upload.php
  • /app/webroot/uploadify/files/ – Must be writable
  • /app/webroot/uploadify/cancel.png

Where app/webroot/uploadify/ and app/webroot/uploadify/files are 2 writable folders (chmod 777 to them both).

Good, so now we have a basic page were we can upload “MyExtensions” files – this can be anything you want. For example “Uploadify files”.
Now we go to process the files. In this example we can read the file for stuff that we want and we will delete it from the server. This is very important to do – you can just copy it somewhere safe out of webroot if you need to have the file for later use – since that folder is public available and it can be viewed by anyone. Afterwards we refresh the parent page – you can just do something else ofcourse.

Create the following action in your MyControllers controller :

public function process_upload($filename) {
    $refresh = "";
    if (file_exists("uploadify/files/".$filename) === false) {
        $this->Session->setFlash('The upload failed. Please try again.','default',array("class" => "notification error"));
    } else {
        $file =  file_get_contents("uploadify/files/".$filename));
        if (!$file) {
            $this->Session->setFlash('The upload failed because the file contents is malformed','default',array("class" => "notification error"));
        } else {
            /*
            * DO STUFF HERE
            */
            $this->Session->setFlash('The file was uploaded succesfully','default',array("class" => "notification confirm"));
            $refresh = "parent.location.reload();";
        }
        /*
        * DELETE OR MOVE YOUR FILE HERE. MAKE SOME CHECKS BEFORE YOU DO THAT THOUGH.
        */
        unlink("uploadify/files/".$filename);
        $this->set("refresh",$refresh);
    }
}

Now for the view of this method:

< div style="margin:15px;">
    < ?php $session->flash();?>
    < script type="text/javascript">
        < ?=$refresh?>
    < /script>
< /div>

And you are done!

Very important things to remember/add:

  • The uploader.swf,upload folder(files) the cancel picture and the script foruploading are all public so remember to harden your security before going with this live
  • The files that you upload will be public thus can be viewed by anyone

Hope you liked it!

  • Sergei
    Great tutorial.
    However it seems that Uploadify is messing with file types and changes all to "application/octet-stream".
    Is there any fix for this?
  • etipaced
    Unfortunately, no. Flash automatically assigns the file type to application/octet-stream. We are stuck parsing file extensions to determine mime type :-/
  • srimathi
    please accept my english....
    Hai i am srimathi from india. i am very new to cakephp. i want to download multiple files in single screen and single table. please tell how to do this. Attach table also. Give the sample project.

    And also i am welling to create website using php. Do you have article means please send it.

    Once more i tell I AM VERY NEW TO SOFTWARE.

    thanks
  • Ash22pk
    hello...i have started to make it work..but the progress bar doesn't show...first the file displays the file name...and than after a second or two...it shows file upload 100 %. can u please help me know whats the problem?? ..is there some kinda image bar that i have to include??
  • Ash22pk
    solved it....wasn't including the css properly :p...
  • Jamessy
    Hi thanks for the tutorial, just wandering about this bit here

    "Create a view with the following contents (these are very important to stick with – try to modify them at your own “risk”):"

    what name and where should I add this view file?
    Any help would be grateful
  • If i am not mistaken (it is some while since i've used cakephp) it should be named prepare_upload.ctp inside the views/mycontrollers/
  • It seems my template sort of messed it up, i'll fix it ASAP. Thanks for the insight ! :)
  • MIchael
    Great, looking forward to it :)

    I'm having a lot of trouble getting uploadify to upload anything..

    I've got it setup for multiple uploads, I can select which files I want but it won't recognise
    my upload method in my controller or if I just point it to /js/uploadify/uploadify.php this doesn't work either.

    Looks like you've got this solved so looking forward to see how it's done :)

  • Done! The key is to point your uploadify to go to your process action from Cake. Then you will basically have the $_FILES array filled in and you can do whatever you want from that point on. Good luck & reply if you still have problems, perhaps I can help.
  • MIchael
    No luck so far :(

    No matter what I put in for 'script' it doesn't seem to be finding it.

    Is there any way you can zip your code as I still can't see it properly?

    Thanks!
  • I can send you the exact text i used via email if you wish (just send me a ping at gabreanuandrei [at] gmail [dot] com and I'll do it.

    Tell me this tough, if you put in your script variable the following:

    'script': 'url(array('controller' => 'some_controller', 'some_upload_action')); ?>', and in that controller/action just echo on the screen "1", what happens?
  • Michael
    Hi there,

    I can't view the upload.ctp file in my browser, could you provide a link to the source code?

    Many thanks
  • I am not sure why that is happening. Check out the other post i have written about integrating it with Zend Framework. I remember i had a problem with error 302 and i was fixed. Try to do it as i did it there (same concepts) and it might just work!
  • Almir Filho
    When i set the 'script' param on jquery to '/project_name/controller/action', uploadify returns HTTP Error 302 (not found). How can i make this works in my controller? i have no idea.. =(
  • sk8te
    Thanks a lot!!!
    It works perfectly!!
    I had to modify my controller to make my existing jqCrop Functionality work.

    Now, its all good! Thanks a lot!! :)
  • azhararmar
    Great piece of information. will try this out..

    Best Regards
  • @Sebastian

    I am not sure what could cause this. Did you try to post a question on the uploadify forums ? Also, take care that there have been changes to the Flash player security and flash uploaders and downloaders work kinda awkward now.. Perhaps this is the problem?
  • Hmmm.... well the entire uploadify is working but when i'm changing debug to 0 the uploadify plugins make me an IO Error ... well... anyone had the same problem !??
  • Victor
    Thanks a lot for sharing!!!
    works really good.
blog comments powered by Disqus


Popular tags

Partner Blogs

Latest tweets


Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Web Analytics