富文本上传图片——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. 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 image and insert in CKEditor. If you want to upload the image to 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 Standard Package of CKEditor plugin. Extract the downloaded CKEditor plugin archive and place it in the root directory. 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 which you want to replace with CKEditor.

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

2. Include the library file of CKEditor jQuery plugin.

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

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

<script>
    CKEDITOR.replace('editor');
</script>

Setup Image Upload URL
Specify some additional config options to CKEDITOR.replace() method for add upload dialog in CKEditor.

Use the filebrowserUploadUrl config property to specify the URL of the image upload script (ck_upload.php).
Setup filebrowserUploadMethod config option to form.

<script>
    CKEDITOR.replace('editor', {
        filebrowserUploadUrl: 'ckeditor/ck_upload.php',
        filebrowserUploadMethod: 'form'
    });
</script>

The above configuration will add an Upload tab on the Image Properties dialog. It allows the user to select a file and send to the server-side script for upload.

ckeditor-image-upload-dialog-send-to-server-php-codexworld.png?w=649&ssl=1uploading.4e448015.gif正在上传…重新上传取消

Upload Image to Server (ckeditor/ck_upload.php)
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 move_uploaded_file() function in PHP.
  • Render image as HTML and return to CKEditor.
  • If the image upload is successful,
  • The upload status will be shown in an alert dialog.

Insert uploaded image in the editor.

<?php 
// Define file upload path 
$upload_dir = array( 
    'img'=> 'uploads/', 
); 
 
// Allowed image properties  
$imgset = array( 
    'maxsize' => 2000, 
    'maxwidth' => 1024, 
    'maxheight' => 800, 
    'minwidth' => 10, 
    'minheight' => 10, 
    'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'), 
); 
 
// If 0, will OVERWRITE the existing file 
define('RENAME_F', 1); 
 
/** 
 * 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 ==1 && file_exists($p .$fn .$ex)){ 
        return setFName($p, F_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 .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight']; 
            } 
 
            if($width < $imgset['minwidth'] || $height < $imgset['minheight']){ 
                $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight']; 
            } 
 
            if($_FILES['upload']['size'] > $imgset['maxsize']*1000){ 
                $re .= '\\n 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_dir, F_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)) { 
            $CKEditorFuncNum = $_GET['CKEditorFuncNum']; 
            $url = 'ckeditor/'. $upload_dir . $f_name; 
            $msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB'; 
            $re = in_array($type, $imgset['type']) ? "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>":'<script>var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\' \', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent();dialog.hide();</script>'; 
        }else{ 
            $re = '<script>alert("Unable to upload the file")</script>'; 
        } 
    }else{ 
        $re = '<script>alert("'. $re .'")</script>'; 
    } 
} 
 
// Render HTML output 
@header('Content-type: text/html; charset=utf-8'); 
echo $re;


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 to upload the images to the server and add automatically to CKEditor. You can easily integrate the server-side image upload functionality in CKEditor without using any plugin.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值