How to Upload Image in TinyMCE Editor using PHP


Image upload is a common feature in the WYSIWYG HTML editor. If you’re using TinyMCE editor in the textarea, the image can be easily inserted in the editor. TinyMCE HTML editor provides an easy option to upload and insert images in the editor as BLOB data type. But it takes time to render BLOB images on the browser. So, server-side upload always a better option to insert image in a TinyMCE editor.

TinyMCE editor supports local file picking and image uploading. But, to make these features functional you required to do some configuration. Also, the server-side upload handler is required to upload image file to the server. In this tutorial, we will show you how to allow the user to upload image in TinyMCE editor using PHP.

This example demonstrates the integration of upload image feature in TinyMCE using images_upload_handler and PHP upload handler. With this feature, the user can upload image from computer and insert in TinyMCE editor. Also, a friendly user-interface (UI) will be provided to simplify the image upload by dropping it from the computer.

HTML Code

Specify an HTML element (myTextarea) to add TinyMCE HTML Editor.

<textarea id="myTextarea"></textarea>

JavaScript Code

At first, include the JS library of TinyMCE plugin.

<script src="tinymce/tinymce.min.js"></script>

The following configuration options enable the local file picker and image upload feature in TinyMCE editor.

  • images_upload_url – Specify a URL for the server-side upload handler. Once this config is defined, an Upload tab will appear in the Image Dialog.
  • images_upload_handler – This config overrides default upload handler to simulate successful upload. This upload handler function takes three arguments – blobInfo, success, and failure. The success callback returns JSON object with location property.
<script>
tinymce.init({
    selector: '#myTextarea',
    plugins: 'image code',
    toolbar: 'undo redo | image code',
    
    // without images_upload_url set, Upload tab won't show up
    images_upload_url: 'upload.php',
    
    // override default upload handler to simulate successful upload
    images_upload_handler: function (blobInfo, success, failure) {
        var xhr, formData;
      
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'upload.php');
      
        xhr.onload = function() {
            var json;
        
            if (xhr.status != 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }
        
            json = JSON.parse(xhr.responseText);
        
            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
        
            success(json.location);
        };
      
        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
      
        xhr.send(formData);
    },
});
</script>

PHP Upload Handler (upload.php)

The following code creates a server-side upload handler to upload image file to the server using PHP.

  • Check whether the file was uploaded via HTTP POST using is_uploaded_file() function in PHP.
  • If the origin is set, check whether it is valid.
  • Verify extension of the file using pathinfo() function in PHP.
  • Upload file to the server using move_uploaded_file() function in PHP.
  • Respond to the successful upload with JSON. Use a location key to specify the path to the saved image resource.
<?php
// Allowed origins to upload images
$accepted_origins = array("http://localhost""http://107.161.82.130""http://codexworld.com");

// Images upload path
$imageFolder "images/";

reset($_FILES);
$temp current($_FILES);
if(
is_uploaded_file($temp['tmp_name'])){
    if(isset(
$_SERVER['HTTP_ORIGIN'])){
        
// Same-origin requests won't set an origin. If the origin is set, it must be valid.
        
if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
            
header('Access-Control-Allow-Origin: ' $_SERVER['HTTP_ORIGIN']);
        }else{
            
header("HTTP/1.1 403 Origin Denied");
            return;
        }
    }
  
    
// Sanitize input
    
if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/"$temp['name'])){
        
header("HTTP/1.1 400 Invalid file name.");
        return;
    }
  
    
// Verify extension
    
if(!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif""jpg""png"))){
        
header("HTTP/1.1 400 Invalid extension.");
        return;
    }
  
    
// Accept upload if there was no origin, or if it is an accepted origin
    
$filetowrite $imageFolder $temp['name'];
    
move_uploaded_file($temp['tmp_name'], $filetowrite);
  
    
// Respond to the successful upload with JSON.
    
echo json_encode(array('location' => $filetowrite));
} else {
    
// Notify editor that the upload failed
    
header("HTTP/1.1 500 Server Error");
}
?>

Image Upload Dialog in TinyMCE

The image icon in the editor’s toolbar opens a dialog box for the image upload. In the Upload tab, you can select image from computer or drag and drop the image directly. The image will be uploaded to the server and HTML will be inserted in the editor.

tinymce-drag-drop-image-upload-php-codexworld

Additional Configuration

By default all URLs are automatically converted to relative URLs. If you want to insert the real URL of the uploaded image, set convert_urls option to false. It will restore URLs to their original values.

convert_urls: false

How to Export TinyMCE Content to MS Word Document

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply