Search code examples
ckeditor

How can you integrate a custom file browser/uploader with CKEditor?


The official documentation is less than clear - what's the correct way to integrate a custom file browser/uploader with CKEditor? (v3 - not FCKEditor)


Solution

  • Start by registering your custom browser/uploader when you instantiate CKEditor. You can designate different URLs for an image browser vs. a general file browser.

    <script type="text/javascript">
    CKEDITOR.replace('content', {
        filebrowserBrowseUrl : '/browser/browse/type/all',
        filebrowserUploadUrl : '/browser/upload/type/all',
        filebrowserImageBrowseUrl : '/browser/browse/type/image',
    filebrowserImageUploadUrl : '/browser/upload/type/image',
        filebrowserWindowWidth  : 800,
        filebrowserWindowHeight : 500
    });
    </script>
    

    Your custom code will receive a GET parameter called CKEditorFuncNum. Save it - that's your callback function. Let's say you put it into $callback.

    When someone selects a file, run this JavaScript to inform CKEditor which file was selected:

    window.opener.CKEDITOR.tools.callFunction(<?php echo $callback; ?>,url)
    

    Where "url" is the URL of the file they picked. An optional third parameter can be text that you want displayed in a standard alert dialog, such as "illegal file" or something. Set url to an empty string if the third parameter is an error message.

    CKEditor's "upload" tab will submit a file in the field "upload" - in PHP, that goes to $_FILES['upload']. What CKEditor wants your server to output is a complete JavaScript block:

    $output = '<html><body><script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$url.'","'.$msg.'");</script></body></html>';
    echo $output;
    

    Again, you need to give it that callback parameter, the URL of the file, and optionally a message. If the message is an empty string, nothing will display; if the message is an error, then url should be an empty string.

    The official CKEditor documentation is incomplete on all this, but if you follow the above it'll work like a champ.