Days
Hours
Minutes
Seconds
x

Froala Editor v4.1.4 is Here LEARN MORE

Skip to content

Handle user profile image using Froala And PHP - Tutorial

In this tutorial, we will learn how to use Froala image uploader tool to upload and remove the images from a PHP server.

Get Started

Following the get started guide, you should now have created an index.php file with the following code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>
      Froala used as image input
      <title>
      <!-- Stylesheets-->
      <link rel="stylesheet" href="css/froala_editor.min.css">
      <link rel="stylesheet" href="css/plugins/image.min.css">
      <link rel="stylesheet" href="css/plugins/image_manager.min.css">
   </head>
   </body>
   <!-- HTML-->
   <div class="form-group">
      <label for=" ">Upload Photo<label>
      <figure>
         <img id="logo" src="https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png" alt="User placeholder" height="100">
         <figcaption>Click on the above image to edit or replace</figcaption>
      </figure>
   </div>
   <!--JS Script-->
   <script src="js/froala_editor.min.js"></script>
   <script src="js/plugins/image.min.js"></script> 
   <script src="js/plugins/image_manager.min.js"></script>
   <script>
      const editor = new FroalaEditor( '#logo',{
      pluginsEnabled: ['image', 'imageManager'],
      //image popup buttons
      imageEditButtons: ['imageReplace', 'imageRemove'],         
       //Buttons for the popup menu which appears on imageReplace button click
      imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
        }
        });
       
   </script>
   </body>
</html>

Step 1: Complete The Form HTML Code

In the code above we have added the image element only. To turn this into a profile form example, let's add a first name, last name, and gender input fields. And let's add the Bootstrap stylesheet to style the form elements.

The folders structure

And the index.php code is

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" >
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Froala used as image input</title>
      <!-- Stylesheets-->
      <link rel="stylesheet" href="css/froala_editor.min.css">
      <link rel="stylesheet" href="css/plugins/image.min.css">
      <link rel="stylesheet" href="css/plugins/image_manager.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
   </head>
   <body>
      <h1>Update Your Profile</h1>
      <!-- start example -->
      <div class="well" style="max-width: 400px;">
      <form action="/person.php" method="post">
         <div class="form-group">
            <label for=" ">Upload Photo
            <label>
               <figure>
                  <img id="logo" src="https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png" alt="User placeholder" height="100">
                  <figcaption>Click on the above image to edit or replace</figcaption>
               </figure>
         </div>
         <div class="form-group">
         <label for="firstname">First Name</label>
         <input class="form-control" type="text" name="firstname" placeholder="Enter your first name">
         </div>
         <div class="form-group">
            <label for="lastname">Last Name</label>
            <input class="form-control" type="text" name="lasttname" placeholder="Enter your last name">
         </div>
         <div>
            <div class="form-group">
               <label>Gender</label>
               <label class= "checkbox-inline">
               <input type="radio" name="gender id="male" value="male">
               </label>
               <label class="checkbox-inline">
               <input type="radio" name="gender" id="female" value="female">
               </label>
            </div>
            <input type="submit" class="btn btn-primary" value="submit">
      </form>
      </div>
      <!--end example-->
      <!--JS Script-->
      <script src="js/froala_editor.min.js"></script>
      <script src="js/plugins/image.min.js"></script>
      <script src="js/plugins/image_manager.min.js"></script>
      <script>
         const editor = new FroalaEditor('#logo',{
         pluginsEnabled: [ 'image', 'imageManager'],
         //image popup buttons
         imageEditButtons: ['imageReplace', 'imageRemove'],         
         //Buttons for the popup menu which appears on imageReplace button click
         imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
            }
            });
      </script>
   </body>
</html>
  

And if you open the index.php file in your browser, you should be able to see:

Froala Initialization Code Explanation

Let’s dig deeper into the Froala initialization code.

      /** The Editor initialization code **/
     <script>
         const editor = new FroalaEditor('#logo',{
         pluginsEnabled: [ 'image', 'imageManager'],
         //image popup buttons
         imageEditButtons: ['imageReplace', 'imageRemove'],         
         //Buttons for the popup menu which appears on imageReplace button click
         imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
       }
       });
   </script>
  

The FroalaEditor constructor function accepts three arguments:

  1. The selector of the element that you want to initialize Froala at.
  2. Options object.
  3. A callback function that will be called once Froala is initialized.

Let's take a look at the option we are using:

  1. pluginsEnabled:

    Froala editor has +30 plugins. In this option you can specify which plugins will be enabled, other plugins will be disabled. Since we are using Froala for image uploading, we will need to enable Image and Image Manager plugins only.

  2. imageEditButtons:

    In this option you can specify the buttons that will appear when the image is clicked, for our use case, we need the upload and remove image buttons which are named 'imageReplace' and 'imageRemove' respectively.

  3. imageInsertButtons

    In this option, you can specify the buttons that will be displayed at the image insert popup menu. You can specify here the options for uploading images as well as a back button to close the popup menu.

By initializing Froala editor as in the above code, you should now be able to see replace and remove options when you click on the image.

Step 2: Download The Froala PHP SDK

Download the Froala PHP SDK using your preferred method. For this demo, We installed the SDK library using the direct link. Then, we created a new folder at the project base folder and extract the SDK files into that folder.

Note: Froala PHP SDK requires FileInFo and Imagick extensions to be enabled. The Imagick extension is required for resizing images. Since we will not resize images in this example, I removed it from the requireDependencies function in the lib/FroalaEditor.php file to not get an error if the extension is not enabled on the server.

Step 3: Upload And Store Images From Your Device To The Server

For this step, we need:

  1. Determine the path of the folder that we will use to store the user image. For this demo purpose, we will store the image at storage\user1\images folder.
  2. Set the imageUploadURL Froala option to the path of a PHP file that will handle the image upload request from the client. this will be a new PHP file that, in this demo, we will create at the base folder of the project with the name upload.php.
  3. Set the request type in the imageUploadMethod option
     <script>
         /** The Editor initialization code **/
         const editor = new FroalaEditor('#logo',{
         pluginsEnabled: [ 'image', 'imageManager'],
         //image popup buttons
         imageEditButtons: ['imageReplace', 'imageRemove'],         
         //Buttons for the popup menu which appears on imageReplace button click
         imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
         //Set the request type
         imageUploadMethod:'POST',
         //Set the image upload URl.
         imageUploadURL:'upload.php'
         });
     </script>
		 
4. In the upload.php file, we have to return an object that has a link property that is the URL of the uploaded image. Froala SDK makes this quite simple by just calling FroalaEditor_Image::upload and passing the image storage path as the first argument.
     <?php
         /** upload.php file **/
     
         require 'sdk/lib/FroalaEditor.php';
         // Store the image.
         try{  
               $response = FroalaEditor_Image::upload('/fro-demos/img/storage/user1/images/');
          //Set the request type
            echo stripslashes(json_encode($response));
            }
             catch(Exception $e) {
            http_response_code(404);
	?>
		 

Note: For the uploaded image to be stored correctly, the server should have the rights to write in the uploads folder. Additionally, you should check that the uploaded image is publicly accessible in the browser so it can be displayed to your users.

Now, if you open the form in the browser and upload an image from your computer, it should be stored at storage\user1\images folder.

Display Uploaded Image Instead Of The Placeholder Image When The Page Is Refreshed

We have two cases:

  1. Store the last uploaded image only and each time a new image is uploaded it will replace the old one. In this case, all we need to do is to check if the storage folder has an image to display. If it doesn't have any image, we will display the placeholder image.
  2. Allowing users to store multiple images in the storage folder. In this case, you'll need to store also the uploaded image filename to use in displaying the image later, in a real application you can store the image filename in the users table in the database, but for this demo we will store it in JSON file at storage\user1\images\image_name.txt.
In this toturial we will implement the second case. Open the upload.php file and add the following line to store the uploaded image filename at the image_name.txt file
    //store image link in a file
    file_put_contents( $_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', $response);		
The full code:

     <?php
       /** upload.php file **/
     
       require 'sdk/lib/FroalaEditor.php';
       // Store the image.
          try {      
                    $response = FroalaEditor_Image::upload('/fro-demos/img/storage/user1/images/');
                    $response = json_encode($response);
                     //store image link in a file
                    file_put_contents( $_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', $response);
                    //return the response
                    echo stripslashes($response);
                    }
                    catch ( Exception $e) {
                    http_response_code( 404);
                 }
	?>
		 

Now, if you open the index.php file in your browser and upload an image from your computer, it should be stored at storage\user1\images and the filename is written in storage\user1\images\image_name.text file

In this case, when the page is loaded and the image_name.text file has an image name, then the server should display that image, otherwise, the placeholder image should be displayed. The following code is just doing this.

Open the index.php file and replace the image display section code with this one

    <div class="form-group">
    <label for=" ">Upload Photo</label>
    <figure>
     <?php
        $project_folder='/fro-demos/img';
          $file_path=$_SERVER['DOCUMENT_ROOT'] . $project_folder . '/storage/user1/images/image_name.txt';      
            $response = file_get_contents($file_path);
             if($response === false || empty($response)){
             $img_src="https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png";
         }
         else
         {
            $response=json_decode($response); {
        $img_src=$response->link;
                 }
	?>
    <img id="logo" src="<?php  echo $img_src; ?>" alt="User placeholder" height="100">
    <figcaption>Click on the above image to edit or replace</figcaption>
    </figure>
    </div> 
    

Step 4: Upload Images From URL To The Server

To upload images from an external URL, you should set the imageCORSProxy option.
Proxy server is needed for reading images inserted by URL and uploading them to your server. For testing, you can:

The message “You currently have temporary access to the demo server.” should appear and if you return to your upload form, you will be able to upload images from URLs

     <script>
        /** The Editor initialization code **/
         const editor = new FroalaEditor('#logo',{
         pluginsEnabled: [ 'image', 'imageManager'],
         //image popup buttons
         imageEditButtons: ['imageReplace', 'imageRemove'],         
         //Buttons for the popup menu which appears on imageReplace button click
         imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
         //Set the request type
         imageUploadMethod:'POST',
         //Set the image upload URl.
         imageUploadURL:'upload.php'
        //Set Proxy to upload images from a URL
        imageCORSProxy:'https://cors-anywhere.herokuapp.com',
         });
     </script>
		 

Step 5: Setup Image Manager

With Froala, an image manager is already created for you. You just need to tell Froala which images to display. To do this you have to set the imageManagerLoadURL option. The editor will send an HTTP request to the imageManagerLoadURL and the server should respond with an array of images objects.

For implementing this, we will create a new PHP file called image_manager.php

Set imageManagerLoadURL option to the path of that file

     <script>
             /** The Editor initialization code **/
         const editor = new FroalaEditor('#logo',{
         pluginsEnabled: [ 'image', 'imageManager'],
         //image popup buttons
         imageEditButtons: ['imageReplace', 'imageRemove'],         
         //Buttons for the popup menu which appears on imageReplace button click
         imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],
         //Set the request type
         imageUploadMethod:'POST',
         //Set the image upload URl.
         imageUploadURL:'upload.php'
         //Set Proxy to upload images from a URL
         imageCORSProxy:'https://cors-anywhere.herokuapp.com',
         //Set the image delete URL.
         imageManagerDeleteURL:'delete_image.php',
         //Set the image upload URL.
        imageManagerLoadURL: 'image_manager.php',
          });
     </script>
		 

In the image_manager.php file you need just to call the FroalaEditor_Image::getList function and pass the image storage path as the first argument. The Froala SDK will return an array of the images objects stored in that folder. All you need to do is to return the images array back to the client.

     <?php
            /** image_manager.php file **/
          
       require 'sdk/lib/FroalaEditor.php',;

          try {      
                    // Get list of the images.
                    $response = FroalaEditor_Image::getList('/fro-demos/img/storage/user1/images/');
                   // return the list of the images to the cleint.
                    echo stripslashes (json_encode($response));
                    }
                    catch ( Exception $e) {
                    http_response_code( 404);
                 }
	?>
		 

Now if you click on image manager button, you should be able to view your images

When you hover over an image inside the Image Manager, two buttons are shown one is for replacing the profile image with the selected image and the other is for removing the selected image.

The first button is for replacing the profile image and it works on the client-side out of the box. But in our demo, we have to update the image_name.txt file when the selected image is replaced to keep the newly selected image displayed when the page is reloaded.

To do this we need to send an HTTP request to the server when the image is replaced which will store the selected image link at the image_name.txt file. Froala doesn't have an option for doing this, but Froala has a variety of events that can help in doing custom requirements.

In our case, we will use the Froala image.replaced event to send an HTTP request to the server. At the following code inside the options object of Froala initializing code

             /** The Events object of the Editor initialization code **/
                events: {
                    'image.replaced': function ($img, response ){ 
                        //this is the editor instance.
                    console.log(this);
                        //get the image link
                    var imgLink = $img[0].src.replace('http://localhost', '');
                        //Send HTTP request to the server
                    var request=new XMLHttpRequest();
                        //set request type and target url
                    request.open('POST', window.location.pathname+'store_image_link.php', true);
                        //Set the data that will be sent along with the request
                    var data=new FormData();
                        //send the link of the replaced image that needs to get stored
                    data.append('img_link', imgLink);
                        //send the request with the data
                    request.onload=function() {   
                    if (this.status >= 200 && this.status < 400) {
                         //request Success!
                   console.log ('Image successfully stored.'); 
                    } 
                    else {
                        //We reached our target server, but it returned an error
                    var err = this.response;
                    console.log ('Image delete problem: ' + JSON.stringify(err));
                        }
                        },
                        //On request failure  
                    request.send = (data)
                    request.onerror = function() {
                        // There was a connection error of some sort
                        var err = this.response;
                    console.log ('Image delete problem: ' + JSON.stringify(err));
                    };
                    }
                    }

It will send an HTTP request to the store_image_link.php file which we will create at the project base folder and it will contain the following code to receive the replaced image link and store it inside the text file.

     <?php
       /** store_img_link.php file **/
         try { 
              //Receive the image link
          $link = json_encode($_POST['img_link']);
            //Store image link in a file
          file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', $link);
            //Return success message to the client.
          echo stripslashes(json_encode('Success'));
            }
          catch (Exception $e) {
            {
           http_response_code(404);
            }
	?>
		 

Since image.replaced event is triggered also when the image is uploaded with the other uploading options, we can remove storing image filename code from the upload.php file. Its contents will be:

     <?php
       /** upload.php file **/
         try { 
              //Receive the image link
          $link = json_encode($_POST['img_link']);
            //Store image link in a file
          file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', $link);
            //Return success message to the client.
          echo stripslashes(json_encode('Success'));
            }
          catch (Exception $e) {
            {
           http_response_code(404);
            }
	?>
		 

We are now storing the image link directly not as a link property. so we need to fromeplace the following code from the index.php file

         $response = json_encode($response);
         $img_src = $response->link;
         
With
         $img_src = json_encode($response);
		 
Displaying the profile image when the page is reloaded should now be working correctly even if it is replaced using the Image Manager.

Step 6: Delete Images

Deleting images is done by sending an HTTP request to the server which will use the Froala SDK to delete the image and return a successful response to the client. Users can delete images in two ways

6.1: Delete Images From Image Popup Menu:

Since we don’t have an option to send a delete request when a user clicks the delete image button from the image popup menu, we will use the image.beforeRemove event to send the request.

If the image is successfully deleted from the server, the client will replace the current image with the placeholder image and alert the user that image is successfully deleted.

In the Froala initialization options parameter, add the following code to the events object

  /**Adding image.beforeRemove event to the Editor initialization code **/

             //delete image from the server
            'image.beforeRemove': function ($img){ 
                //get the image link
            var imgLink = $img[0].src.replace('http://localhost', '');
                //Send HTTP request to the server
            var request=new XMLHttpRequest();
                //set request type and target url
            request.open('POST', window.location.pathname+'store_image_link.php', true);
                //Set the data that will be sent along with the request
            var data=new FormData();
                //send the link of the replaced image that needs to get stored
            data.append('src', imgLink);
                //send the request with the data
            request.send(data);   
            request.onload = function() {   
            if (this.status >= 200 && this.status < 400) {
                //Success!
            const placeholder = document.getElementById('logo');
            placeholder.src "https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png";
                 //Display alert to the user
            alert ('Image was successfully deleted');
                     } 
            else {
                //We reached our target server, but it returned an error
            var err = this.response;
            console.log ('Image delete problem: ' + JSON.stringify(err));
                }
                };
                //On request failure  
            request.onerror = function() {
                // There was a connection error of some sort
            var err = this.response;
            console.log ('Image delete problem: ' + JSON.stringify(err));
                   };
                //return false to prevent Froala from removing img src before the HTTP request is completed
            return false;
         },

It will send an HTTP request to the delete_image.php file which we will create at the project base folder and it will contain the following code to delete the image from the server by calling FroalaEditor_Image::delete and set the image link as the first argument. It also will delete the image link from the image_name.txt file.

     <?php
       /** delet_image.php file **/
         try { 
              //Receive the image link
          $link = json_encode($_POST['img_link']);
            //Delete image link from a file
          file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', null);
            //Return success message to the client.
          echo stripslashes(json_encode('Success'));
            }
          catch (Exception $e) {
            {
           http_response_code(404);
            }
	?>
		 

6.2 Delete Images From Image Manager

For deleting images from the ImageManager, Froala provides three options imageManagerDeleteURL, imageManagerDeleteMethod, and imageManagerDeleteParams. We will use the imageManagerDeleteURL option to send an HTTP request to the server when an image is deleted. We will the HTTP request to the same delete_image.php file that we have used in step 6.1 to delete the selected image from the server. Since ImageManager has multi-images, we need to check if the image that will be deleted is the same one that is used as the profile image before removing the image link from the image_name.txt file.

1. Set the imageManagerDeleteURL option to delete_image.php
        // Set the image manager delete URL.
        imageManagerDeleteURL:  'delete_image.php',
            
2. Edit delete_image.php to get the active profile image link and check if it is the same as the image that will be deleted link. If it is then delete the image link from the image_name.txt file.
            <?php
                    /*** deleted_image.php file ***/
              require 'sdk/lib/FroalaEditor.php',;
                try {
                    //get the image to be deleted link
                    $deleted_img_link = $_POST('src');
                     //Delete image from the server
                    $response = FroalaEditor_Image::delete($deleted_img_link);
                     //Check the image link is the profile image link or not
                    //get the used profile image
                    $profile_img_link = file_get_contents( $_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt');
                    //if a profile image is used and it is the one that will be deleted
                    if($profile_img_link !== false && !empty($profile_img_link) && json_decode($profile_img_link) === $deleted_img_link);
                    //Delete the image link from the txt file
                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', null)
                    {
                    //Return a success message to the client.
                    file_put_contents(json_encode('Success'))
                    }
                    catch(Exception $e) {
                    http_response_code( 404);
                    }
	?>
		 

Note: the image to be deleted link will be available at $_POST['src'] global variable.

3. Finally, The client should replace the profile image with the placeholder image If the deleted image is the same as the profile image. To do this we will use the imageManager.imageDeleted event. This event's first parameter is the response of the server to the request sent by imageManagerDeleteURL option which is the response we return in the delete_image.php script.

Edit the delete_image.php file to return a response indicating if the image that will be deleted is the profile image or not.

            <?php
                    /*** delet_image.php file ***/
              require 'sdk/lib/FroalaEditor.php',;
            try {
                    /** set a flag to indicate if the image to be deleted is the profile image**/
                    /** Used when deleting image from image manager **/
                    $is_profile_img  = false;
                     //get the image to be deleted link
                    $deleted_img_link  = $_POST['src']; 
                     //Delete image from the server
                    $response = FroalaEditor_Image::delete($deleted_img_link);
                     //Check the image link is the profile image link or not
                    //get the used profile image
                    $profile_img_link = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt');
                    //if a profile image is used and it is the one that will be deleted
                    if($profile_img_link !== false && !empty($profile_img_link) && json_decode($profile_img_link) === $deleted_img_link);
                    //this is the image used for profile
                     $is_profile_img = true;
                    //Delete the image link from the txt file
                    file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', null)
                    }
                     //Return the response to the client.
                    echo stripslashes(json_encode(["is_profile_img"=>$is_profile_img]));
                    }
                    catch(Exception $e) {
                    http_response_code( 404);
                    }
	?>
		 

In the imageManager.imageDeleted event check if the response is indicating that the image to be deleted is the profile image, if it is, replaces it on the form with the placeholder image.

                //delete image from the Image Manager
            'imageManager.imageDeleted': function (response) 
             response = JSON.parse(response);
            if(response.is_profile_img'){
                 //replace profile image with the placeholder image
            const placeholder = document.getElementById('logo');
            placeholder.src = "https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png";
            }
            },

Step 7: Image Validation

7.1: Image Validation On The Client-side

Froala editor provides imageAllowedTypes and imageMaxSize options that can be used to validate image type and image size respectively at the client-side. Moreover, you can use image.beforeUpload (images) event to do any custom validation.

             //Validation
            //set image allowed types
            imageAllowedTypes: ['jpeg', 'jpg', 'png'] 
             // Set max image size to 10MB.
            imageMaxSize: 1024 * 1024 * 10,

Note: Even if you are using client-side validation, server-side validation is also recommended.

7.2: Image Validation On The Server-side

In step 3, we have used the FroalaEditor_Image::upload method to upload the image to the server. This method accepts a 2nd optional parameter which is an uploading options array.

Image extension and image mime type validation can be done on the server using Froala SDK as described in this reference.

Other validations types, e.g. Image size validation can be done by assigning a custom function to the “validation” array.

In our demo, we would allow uploading 'jpeg', 'jpg', and 'png' images only. To do that we will edit upload.php file
            <?php
                    /**** upload.php file***/
              require 'sdk/lib/FroalaEditor.php',;
            try {
                    $options = array(
                    'validation' => array(
                    'allowedExts' => array('jpeg', 'jpg', 'png'),
                    'allowedMimeTypes' => array('image/jpeg', 'image/pjpeg', 'image/x-png', 'image/png')
                    )
                    );
                    // Store the image.
                    $response = FroalaEditor_Image::upload(/fro-demos/img/storage/user1/images/', $options'); 
                    //return the response
                    echo stripslashes(json_encode($response));
                    }
                    catch(Exception $e) {
                    http_response_code( 404);
                    }
                ?>
		 

Download The Tutorial Full Code

We reach the end of our tutorial. You can download the full code form GitHub and get started immediately. If you like this tutorial please star the GitHub repository, this will encourage us to create more tutorials.

However, our tutorial code ends here, we don’t cover all what Froala is capable of helping you in. Some of what we didn’t cover in the downloaded code is discussed below.

Step 8: Handling errors while uploading Images

By default, Froala displays an error message when an error happens during image upload but if you want to customize how or what is displayed, you can use image.error and imageManager.error events to do so.

Step 9: Resize Image

9.1: Resize Image On The Client-Side

Froala allows users to resize the profile image while they are viewing it on the browser, but this doesn’t affect the physical size of the image. Unless you use Froala events or other ways to send the image size to the server, the image will return to its original size once you reload the page.

9.2: Resize Image On The Server-Side

Froala SDK will help you to automatically resize the uploaded image to a certain size. Follow this reference. to achieve that.

Note: Make sure that PHP Imagick extension is enabled on your server or an error will be will thrown.

Step 10: Upload Images To S3

Froala SDK provides different methods to handle uploading images to S3 which will base your product integration with S3 fast and easy. Uploading images to S3 is out of the scope of this tutorial, but you can use this reference to guide you implementing this.

Step 11: Allow Users To Add A Rich Content Profile Description

It’s common to have a text-area field for allowing users to enter a description about their profile. Using Froala WYSIWYG editor you can allow your users to improve their description content by allowing them to style and format their content, Moreover, your users will be able to add videos, images, tables, and links to get a better profile layout and description. All this could be achieved with the same Froala script we have used for image uploading, which means there are no more libraries or resources to take care of. and it is easy to be added to your form.

1. Add the normal textarea field

  
 <div class="form-group">
 <label for="description">Description</label>
 <textarea class="form-control" id="description" name="description" placeholder="Enter a profile description">
 </textarea>
 </div>
 

2. Initialize a new editor on it.

  
 new FroalaEditor('#description');
 

You have a 30 days trial to try Froala WYSIWYG editor for free then you should purchase one of these plans.

[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_188323114" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_676181504" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>
[class^="wpforms-"]
[class^="wpforms-"]
[bws_google_captcha]
<div class="gglcptch gglcptch_v2"><div id="gglcptch_recaptcha_274038687" class="gglcptch_recaptcha"></div> <noscript> <div style="width: 302px;"> <div style="width: 302px; height: 422px; position: relative;"> <div style="width: 302px; height: 422px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=6Ld6lNoUAAAAAM626LfCOrnkBFJtYZAKESFCjgv_" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe> </div> </div> <div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1; border-radius: 3px; height: 60px; width: 300px;"> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px !important; height: 40px !important; border: 1px solid #c1c1c1 !important; margin: 10px 25px !important; padding: 0px !important; resize: none !important;"></textarea> </div> </div> </noscript></div>