How to Insert Image to Servers using TINYMCE Editor Using PHP


Hello Friends, In this tutorial we will learn how to insert an image to servers using TinyMCE editor with PHP code, you can follow these steps:

First, make sure you have a form that allows the user to upload an image. You can create a simple form with an input field of type file, like this:

<form method="post" action="upload.php" enctype="multipart/form-data">
     <input type="file" name="image">
     <input type="submit" name="submit" value="Upload">
</form>

In your PHP script (in this example, "upload.php"), you can handle the file upload using the $_FILES superglobal. Here's an example code snippet:

// Check if the image file was uploaded successfully
if(isset($_FILES['image']) &amp;&amp; $_FILES['image']['error'] == 0) {
    // Define the target directory where you want to save the uploaded image
    $targetDir = "uploads/";

     // Define the file name and path of the uploaded image
     $fileName = basename($_FILES["image"]["name"]);
     $targetFilePath = $targetDir . $fileName;

      // Move the uploaded image to the target directory
     if(move_uploaded_file($_FILES["image"]["tmp_name"], $targetFilePath)){
         echo "The file ". $fileName . " has been uploaded.";
     } else{
          echo "Sorry, there was an error uploading your file.";
     }
}

Once the image has been uploaded to the server, you can use the TinyMCE editor to insert the image into your content. Here's an example code snippet:

// Get the URL of the uploaded image
$imageUrl = "http://example.com/" . $targetFilePath;

// Initialize the TinyMCE editor
tinymce.init({
  selector: 'textarea',
  plugins: 'image',
  toolbar: 'image',
  image_uploadtab: true,
  images_upload_url: 'upload.php',
  images_upload_base_path: '/',
  images_upload_credentials: true,
  images_reuse_filename: true,
  images_dataimg_filter: function(img) {
    return img.hasAttribute('data-mce-object');
  },
  file_picker_types: 'image',
  file_picker_callback: function(callback, value, meta) {
    if (meta.filetype == 'image') {
      callback(imageUrl, {alt: ''});
    }
  }
});

This code initializes the TinyMCE editor with the necessary options for inserting an image, including the URL of the uploaded image and the upload script URL. When the user clicks on the image button in the editor, it will open a file picker dialog that allows them to choose the uploaded image. Once they select the image, it will be inserted into the content with the specified URL and alt text. 

       

Advertisements

ads