How to Add and Upload an Image using CKEditor

If you’ve not heard of CKEditor, it’s a free and open-source rich text HTML editor for use on websites such as this one. In fact, I’m typing into a CKEditor text box right now as I write this article via our administration back-end of the web site. It’s useful for Content Management Systems, Blogs, or anywhere else where you need you users to be able to enter rich text and change styles such as font, size and colour but without the need for technical expertise. Even for those of us who are happy using HTML, it is still a far more elegant and professional-looking way of entering content into a site.

CKEditor, and FCKEditor which came before it, are both great pieces of (did I mention it’s free?!) software. However, compliments dispensed with it’s time for a criticism: the documentation isn’t wonderful. It’s better than it used to be and is getting better all the time, but it’s still not perfect so you may struggle finding out how to add and upload images.

If you’ve stumbled upon this article then you probably want to know how to set up CKEditor to allow you to add images into documents that you publish to your web site’s Content Management System, Blog or other area with user-generated content. And not only how to insert images, but how to upload them to your web site’s server too. Like all things, it’s easy when you know how but until you have those little bits of essential information, it can be a bit of a minefield.

This guide is for PHP users and was originally written for the then-latest version of CKEditor as of October 2010 which was 3.4.1. It has since been updated (in September 2010) for version 3.6.1 to take into account some changes made to CKEditor – these are highlighted in red. Naturally, some parts of it may have changed since then with updates, etc. so if this doesn’t work for you then just leave a comment below and I’ll update the article if I need to. I’m assuming that you already have CKEditor set up and working on your web site. If you haven’t, then you need to do that first!

Step 1: Make sure your CKEditor instance includes an “Insert Image” button

To do this, you simply add ‘Image’ to your toolbar options. If you’re using PHP, then your function will need to look something like this:

function richTextBox($fieldname, $value = “”) {

   
   $CKEditor = new CKEditor();
   $config[‘toolbar’] = array(
    array( ‘Bold’, ‘Italic’, ‘Underline’, ‘Strike’),
    array(‘JustifyLeft’, ‘JustifyCenter’, ‘JustifyRight’, ‘JustifyBlock’),
    array(‘Format’),
    array( ‘Font’, ‘FontSize’, ‘FontColor’, ‘TextColor’),
    array(‘Cut’, ‘Copy’, ‘Paste’, ‘PasteText’, ‘PasteFromWord’ ),
    array(‘Image’, ‘Table’, ‘NumberedList’, ‘BulletedList’, ‘-‘, ‘Outdent’, ‘Indent’, ‘Blockquote’),
    array(‘Subscript’,’Superscript’),
    array( ‘Link’, ‘Unlink’ ),
    array(‘Source’)
   );
   $CKEditor->basePath = ‘/ckeditor/’;
   $CKEditor->config[‘width’] = 975;
   $CKEditor->config[‘height’] = 400;
   
   $CKEditor->editor($fieldname, $value, $config);
}

Notice the Image option highlighted in red. If it’s not there, add it in to your function then hit reload on the page your CKEditor text box is on. The button to add an Image into your text should magically appear!

Step 2: Enable the file upload dialogue box

1288278954_upload_image

Then, you’ll need to unhide the Upload option (pictured). You’ll need to open up the JavaScript file which contains settings related to the Image Properties window. This might look a bit daunting, but don’t worry; if you follow these instructions to the letter then you’ll be fine!

Find the directory in your web site where you’ve saved and extracted CKEditor, and then it’s a couple more directories further down we need to go:

ckeditor\plugins\image\dialogs

Inside that folder is a file called image.js – open this up. If you haven’t already got it, I’d recommend the brilliant Notepad++ to use rather than the basic Notepad programme which comes free with Windows.

You then want to hit CTRL+F to bring up a search box, and search for config.filebrowserBrowseUrl. Shortly after that text you will see the value hidden:true; – change it to hidden:false; 

Update: in later versions of CKEditor, this may have changed to filebrowserImageBrowseLinkUrl so if you can’t find the value listed above, try searching for that instead.

Next, do the same for the value just after the string ‘Upload’.

Voilà! You should now have the options as shown in the screenshot, but it won’t yet work if you try to use it. Read on for how to programme it to work…

Step 3: Telling CKEditor where your image upload script lives

At the root of the CKEditor folder hierarchy is a file called config.js – open up this file and it should have hardly anything in it, apart from a blank-looking function like this: CKEDITOR.editorConfig = function( config )

You just need to add a line inside this function (inside the curly braces) to tell CKEditor where the script lives which will handle the uploaded image files. In our case, this line is as follows: config.filebrowserUploadUrl = ‘../ckupload.php’; – easy.

Note: depending on your server’s setup you may need to provide the full, absolute URL to your PHP script. A relative URL like in the example above is preferable as you will be able to move your web app from one server to another with less headaches, so try that first but if it doesn’t work then just use the full URL.

Following so far? Good, we’re very nearly there!

Step 4: Writing the script to handle the image upload in PHP

If you need a refresher on handling uploaded files in PHP, check out PHP’s superb documentation. It’s at this point that I’ll point out how important it is to perform validation checks on anything which you allow users (even validated users) to upload to your web site’s server. Just because you’re expecting a lovely JPG or PNG image, doesn’t mean that’s what you’re gonna get. If you don’t stop me, I could write a PHP script to download the entire contents of your database’s members or users table, stealing their passwords and other personal data. Don’t be sloppy!

With that firmly in the forefront of your mind, here is a sample ckupload.php script to handle the uploaded image files:

<? 

$url = ‘../images/uploads/’.time().”_”.$_FILES[‘upload’][‘name’];

 //extensive suitability check before doing anything with the file…
    if (($_FILES[‘upload’] == “none”) OR (empty($_FILES[‘upload’][‘name’])) )
    {
       $message = “No file uploaded.”;
    }
    else if ($_FILES[‘upload’][“size”] == 0)
    {
       $message = “The file is of zero length.”;
    }
    else if (($_FILES[‘upload’][“type”] != “image/pjpeg”) AND ($_FILES[‘upload’][“type”] != “image/jpeg”) AND ($_FILES[‘upload’][“type”] != “image/png”))
    {
       $message = “The image must be in either JPG or PNG format. Please upload a JPG or PNG instead.”;
    }
    else if (!is_uploaded_file($_FILES[‘upload’][“tmp_name”]))
    {
       $message = “You may be attempting to hack our server. We’re on to you; expect a knock on the door sometime soon.”;
    }
    else {
      $message = “”;
      $move = @ move_uploaded_file($_FILES[‘upload’][‘tmp_name’], $url);
      if(!$move)
      {
         $message = “Error moving uploaded file. Check the script is granted Read/Write/Modify permissions.”;
      }
      $url = “../” . $url;
    }
$funcNum = $_GET[‘CKEditorFuncNum’] ;
echo “<script type=’text/javascript’>window.parent.CKEDITOR.tools.callFunction($funcNum, ‘$url’, ‘$message’);</script>”;
?>
Basically, we check that there has actually been a file uploaded, and that it’s not empty. Then, most importantly, we check it’s actually a JPG or PNG. We do this by checking its MIME type (and NOT by checking its file extension – any hacker could upload a .exe file renamed to .jpg, then rename back to .exe after the check). We also do one final check to make sure the file we’re dealing with is definitely the file we think we’re dealing with. If that’s all fine and dandy, we then use PHP’s move_uploaded_file() function to move and rename the file.
You’ll notice at the start of the script I’ve included a current Unix timestamp in the filename. Since this will always be unique, that means that all files uploaded to the folder of uploaded files will never have the same filename. Otherwise, one author might upload a file called fred.jpg to include in his article. If, some months later, he/she or another author wants to upload a file with the same name for another article about someone else called Fred, the first one would get overwritten due to identical filenames. Including a timestamp is a somewhat crude way of getting around this, but it works!
Regardless of the outcome of the PHP if…else statements, which have hopefully resulted in the uploaded file being accepted and saved, we echo a bit of JavaScript to the browser which passes information back to CKEditor’s Image Properties box. This contains the URL of where we’ve saved the image, and a message if needed. I’ve included a message for the error scenarios, but there’s no need for a message indicating successful upload, as this will be obvious anyway.

Step 5: Grant Correct File Permissions to your PHP Script

If you’re using IIS to host your web site, you may need to ask your host to set the correct permissions to the folder in which you want to save the image. You need to give Read and Write permissions to the following user: fred\IUSR_caeus.com where “fred” is the machine name and replace “caeus.com” with the name of your site (the user to which the permissions are to be granted). Also, double-check that the directory you’re telling PHP to move your images to does actually exist on your web server.

Conclusion

So there we have it – you should now be able to upload and save images to your web site via the CKEditor rich-text box, and insert them into your document too.
If this article has helped you out, or you have any other comments, then please leave a comment in the box below and don’t forget to click the buttons to share on Facebook and Twitter!

Leave a Reply

Your email address will not be published. Required fields are marked *