Image Upload through CKEditor Using HTML & PHP

edited October 2023 in PHP

1) First Download CKEditor from it's official website https://ckeditor.com/ckeditor-4/download/

(Recommended to download standard package) Extract this downloaded ZIP File in your project

Include your CKEditor as <script src="<?php echo base_url()?>common_assets/ckeditor/ckeditor.js"></script>

2) Replace your normal html textarea with CKEditor as

CODE:

<textarea type="text" name="description" id="description" required class="mb-5"></textarea> 

<script>

CKEDITOR.replace('description',{

            height: 150,

            filebrowserUploadUrl: "<?php echo base_url()?>common_assets/ckeditor/upload.php"

        });

</script>

Here, filebrowserUploadUrl will open a dialog box through which we can upload our image.




3) Now we need to create a upload.php file in our CKEditor folder to handle image upload

//CKeditor upload operation

<?php 

if(isset($_FILES['upload']['name']))

{

 $file = $_FILES['upload']['tmp_name'];

 $file_name = $_FILES['upload']['name'];

 $file_name_array = explode(".", $file_name); 

 $extension = end($file_name_array);

 $new_image_name =rand() . '.' . $extension; 

        if($extension!= "jpg" && $extension != "png" && $extension != "jpeg" && $extension != "PNG" && $extension != "JPG" && $extension != "JPEG") {

    

    echo "<script type='text/javascript'>alert('Sorry, only JPG, JPEG, & PNG files are allowed. Close image properties window and try again');</script>";

}

 elseif($_FILES["upload"]["size"] > 1000000) {

  

 echo "<script type='text/javascript'>alert('Image is too large: Upload image under 1 MB . Close image properties window and try again');</script>";

}

else 

{

 move_uploaded_file($file, 'uploads/' . $new_image_name); 

  $function_number = $_GET['CKEditorFuncNum'];

  $url = 'upload_path'.$new_image_name; //Set your path

  $message = '';

  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";   

} 

}

?>


4) Replace your actual path with upload_path in this code


5) add this line in your config.js of CKeditor

config.filebrowserUploadMethod = 'form';


By following these steps you can upload a image through CKEditor

Sign In or Register to comment.