Upload and Insert Image in CKEditor using PHP

CKEditor plugin provides the easiest way to add WYSIWYG Editor to the input field on the web form. Generally, the WYSIWYG editor is used to replace the textarea for submitting the HTML content. You can easily add WYSIWYG editor to textarea with CKEditor plugin. The CKEditor plugin allows the user to insert HTML content in the textarea field and submit formatted text content to the server side.

The Image plugin of CKEditor helps to insert the image in the editor. In this case, you need to specify the URL of the image to insert into the editor content. The Image plugin is not allowed to upload images and insert them in CKEditor. If you want to upload the image to the server and insert this image in the editor content, custom image upload functionality needs to be integrated into CKEditor. In this tutorial, we will show you how to upload image in CKEditor and insert the uploaded image into the editor content using PHP.

Before getting started, download the latest version of the CKEditor 5 Classic Package. Extract the downloaded CKEditor plugin archive and place it in the root directory.

  • In this example, we will use a Simple upload adapter to integrate server-side image upload functionality. So. make sure you selected the Simple upload adapter plugin at the time of creating the CKEditor build for download.

Note that: You don’t need to download the CKEditor separately, all the required files are included in our source code.

Add CKEditor to Textarea

1. Create a textarea element that you want to replace with CKEditor.

<textarea name="editor" id="editor"></textarea>

2. Include the library file of the CKEditor jQuery plugin.

<script src="ckeditor/build/ckeditor.js"></script>

3.  Use the ClassicEditor.create() method to initialize the CKEditor plugin and replace the textarea element with the WYSIWYG editor.

<script>
ClassicEditor
    .create( document.querySelector( '#editor' ) )
    .catch( error => {
        console.error( error );
    } );
</script>

Setup Image Upload URL

Specify some additional config options to the ClassicEditor.create() method to enable the server-side upload feature in CKEditor.

  • In the simpleUpload config option, use the uploadUrl property to specify the URL of the image upload server-side script (ck_upload.php).
ClassicEditor
    .create( document.querySelector( '#editor' ), {
        simpleUpload: {
            // The URL that the images are uploaded to.
            uploadUrl: 'ckeditor/ck_upload.php',
        }
    } )
    .then( editor => {
        window.editor = editor;
    } )
    .catch( err => {
        console.error( err.stack );
    } );

The above configuration will enable the server-side image upload option. It allows the user to select a file and send it to the server-side script for upload.

Upload Image to Server (ckeditor/ck_upload.php)

First, create a folder to store the uploaded image files on the server. In this example script, we will upload and store the image files in the ckeditor/uploads/ folder.

The ck_upload.php file handles the file upload process using PHP.

  • Specify the upload directory and allowed image properties.
  • Validate image type and size.
  • Upload image to the server using the move_uploaded_file() function in PHP.
  • Specify the uploaded image path in the url property of the response array.
  • Return the response in JSON format using json_encode() function in PHP.
  • If the image upload is successful,
    • The upload status will be shown in an alert dialog.
    • Insert the uploaded image in the editor.
<?php 
// Define file upload path
$upload_dir = array(
    
'img'=> 'uploads/',
);

// Allowed image properties 
$imgset = array(
    
'maxsize' => 5000,
    
'maxwidth' => 4096,
    
'maxheight' => 3000,
    
'minwidth' => 10,
    
'minheight' => 10,
    
'type' => array('bmp''gif''jpg''jpeg''png'),
);

// If 0, will OVERWRITE the existing file
define('RENAME_F'1);

$site '';

/**
 * Set filename
 * If the file exists, and RENAME_F is 1, set "img_name_1"
 *
 * $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
 */
function setFName($p$fn$ex$i){
    if(
RENAME_F ==&& file_exists($p .$fn .$ex)){
        return 
setFName($pF_NAME .'_'. ($i +1), $ex, ($i +1));
    }else{
        return 
$fn .$ex;
    }
}

$re '';
if(isset(
$_FILES['upload']) && strlen($_FILES['upload']['name']) > 1) {

    
define('F_NAME'preg_replace('/\.(.+?)$/i'''basename($_FILES['upload']['name'])));  

    
// Get filename without extension
    
$sepext explode('.'strtolower($_FILES['upload']['name']));
    
$type end($sepext);    /** gets extension **/
    
    // Upload directory
    
$upload_dir in_array($type$imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
    
$upload_dir trim($upload_dir'/') .'/';

    
// Validate file type
    
if(in_array($type$imgset['type'])){
        
// Image width and height
        
list($width$height) = getimagesize($_FILES['upload']['tmp_name']);

        if(isset(
$width) && isset($height)) {
            if(
$width $imgset['maxwidth'] || $height $imgset['maxheight']){
                
$re .= ' Width x Height = '$width .' x '$height .' >>> The maximum Width x Height must be: '$imgset['maxwidth']. ' x '$imgset['maxheight'];
            }

            if(
$width $imgset['minwidth'] || $height $imgset['minheight']){
                
$re .= ' Width x Height = '$width .' x '$height .' >>> The minimum Width x Height must be: '$imgset['minwidth']. ' x '$imgset['minheight'];
            }

            if(
$_FILES['upload']['size'] > $imgset['maxsize']*1000){
                
$re .= ' >>> Maximum file size must be: '$imgset['maxsize']. ' KB.';
            }
        }
    }else{
        
$re .= 'The file: '$_FILES['upload']['name']. ' has not the allowed extension type.';
    }
    
    
// File upload path
    
$f_name setFName($_SERVER['DOCUMENT_ROOT'] .'/'$upload_dirF_NAME".$type"0);
    
$uploadpath $upload_dir $f_name;

    
// If no errors, upload the image, else, output the errors
    
if($re == ''){
        if(
move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
            
$url $site.'ckeditor/'$upload_dir $f_name;
            
$msg F_NAME .'.'$type .' successfully uploaded! >>> Size: 'number_format($_FILES['upload']['size']/10242'.''') .' KB';
            
$response = [
                
'url' => $url
            
];
        }else{
            
$response = [
                
'error' => [
                    
'message' => 'Unable to upload the file!'
                
]
            ];
        }
    }else{
        
$response = [
            
'error' => [
                
'message' => 'Error: '.$re
            
]
        ];
    }
}

// Return response in JSON format
echo json_encode($response);
?>

Save WYSIWYG Editor Content in Database using PHP and MySQL

Conclusion

Our example script helps you to add custom image upload functionality in CKEditor using PHP. It allows you to upload the images to the server and add them automatically to CKEditor. You can easily integrate the server-side image upload functionality in CKEditor without using any plugin.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

5 Comments

  1. Joshua Said...
  2. Vikash Gupta Said...
  3. Hector Neyro Said...
  4. Parth Said...
  5. Marya Said...

Leave a reply

keyboard_double_arrow_up