Replace Image by Uploading a New One Php

Handle user profile paradigm using Froala And PHP - Tutorial

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

  • Step i: Complete The Form HTML Code
  • Froala Initialization Code Caption
  • Stride ii: Download The Froala PHP SDK
  • Stride 3: Upload And Shop Images From Your Device To The Server
  • Display The Uploaded Image Instead Of The Placeholder Image When A Page Is Refreshed
  • Step 4: Upload Images From URL To The Server
  • Step five: Setup Image Director
  • Step vi: Delete Images
    • 6.1: Delete Images From Paradigm Popup Menu
    • 6.ii: Delete Image from The ImageManager
  • Step 7: Epitome Validation
    • 7.i: Image Validation On The Client-side
    • vii.ii: Prototype Validation On The Server-side
  • Download The Total Code
  • Step eight: Treatment Errors While Uploading Images
  • Footstep nine: Resize Images
    • 9.1: Resize Images On The Customer-side
    • ix.2: Resize Images On The Server-side
  • Step x: Upload Images To S3
  • Step 11: Add together A Reach Text Editor To Your Course

Go 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="10-UA-Uniform"                  content="IE=edge">                <meta                  name="viewport"                  content="width=device-width, initial-scale=one.0">                <title>                Froala used as epitome input                <title>                <!-- Stylesheets-->                <link                  rel="stylesheet"                  href="css/froala_editor.min.css">                <link                  rel="stylesheet"                  href="css/plugins/paradigm.min.css">                <link                  rel="stylesheet"                  href="css/plugins/image_manager.min.css">                </caput>                </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"                  meridian="100">                <figcaption>Click on the to a higher place image to edit or replace</figcaption>                </figure>                </div>                <!--JS Script-->                <script                  src="js/froala_editor.min.js">                                </script>                <script                  src="js/plugins/prototype.min.js">                                </script>                <script                  src="js/plugins/image_manager.min.js">                                </script>                <script>                                  const                  editor =                  new                  FroalaEditor(                  '#logo',{                  pluginsEnabled: ['epitome',                  '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>              

Stride 1: Complete The Form HTML Code

In the code to a higher place we accept added the image element simply. To turn this into a contour grade example, let's add together a first proper noun, last proper name, and gender input fields. And let'southward 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-viii"                  >                <meta                  http-equiv="Ten-UA-Uniform"                  content="IE=edge">                <meta                  proper name="viewport"                  content="width=device-width, initial-calibration=ane.0">                <title>Froala used as prototype 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.vi/css/bootstrap.min.css">                </head>                <body>                <h1>Update Your Profile</h1>                <!-- first example -->                <div                  course="well"                  style="max-width: 400px;">                <class                  action="/person.php"                  method="post">                <div                  class="form-group">                <label                  for=" ">Upload Photograph                <characterization>                <figure>                <img                  id="logo"                  src="https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png"                  alt="User placeholder"                  height="100">                <figcaption>Click on the in a higher place image to edit or replace</figcaption>                </effigy>                </div>                <div                  class="form-group">                <label                  for="firstname">Starting time Name</label>                <input                  class="course-control"                  type="text"                  name="firstname"                  placeholder="Enter your offset name">                </div>                <div                  class="form-group">                <characterization                  for="lastname">Last Name</label>                <input                  class="course-command"                  type="text"                  proper name="lasttname"                  placeholder="Enter your terminal name">                </div>                <div>                <div                  class="form-grouping">                <characterization>Gender</label>                <label                  class=                  "checkbox-inline">                <input                  type="radio"                  proper name="gender id="                  male person"                  value="male">                </label>                <label                  class="checkbox-inline">                <input                  type="radio"                  name="gender"                  id="female person"                  value="female">                </label>                </div>                <input                  type="submit"                  course="btn btn-primary"                  value="submit">                </grade>                </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>                </trunk>                </html>              

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

Froala Initialization Code Caption

Let'due south dig deeper into the Froala initialization code.

                                  /** The Editor initialization lawmaking **/                <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 role accepts 3 arguments:

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

Permit'due south take a look at the choice nosotros 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 volition appear when the image is clicked, for our use case, nosotros demand the upload and remove image buttons which are named 'imageReplace' and 'imageRemove' respectively.

  3. imageInsertButtons

    In this option, y'all tin specify the buttons that volition be displayed at the image insert popup menu. You lot can specify hither the options for uploading images as well as a back button to shut the popup menu.

By initializing Froala editor every bit in the in a higher place code, you should now exist able to see supplant and remove options when you click on the image.

Footstep 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 straight link. Then, we created a new folder at the project base of operations binder 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.

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

For this step, nosotros demand:

  1. Determine the path of the folder that we will use to store the user image. For this demo purpose, we will shop the image at storage\user1\images folder.
  2. Set the imageUploadURL Froala selection to the path of a PHP file that will handle the image upload asking from the client. this will be a new PHP file that, in this demo, nosotros will create at the base folder of the project with the name upload.php.
  3. Prepare the request type in the imageUploadMethod option
                <script>                                  /** The Editor initialization code **/                                  const editor = new FroalaEditor(                '#logo',{                                  pluginsEnabled: [                  'paradigm', 'imageManager'],                                  //prototype popup buttons                                  imageEditButtons: ['imageReplace', 'imageRemove'],                                  //Buttons for the popup menu which appears on imageReplace push click                                  imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],                //Ready the asking type                imageUploadMethod:'Post',                //Prepare 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 paradigm. Froala SDK makes this quite simple past just calling FroalaEditor_Image::upload and passing the image storage path equally the first argument.

                <?php                                  /** upload.php file **/                                  require                  'sdk/lib/FroalaEditor.php';                                  // Store the epitome.                                  effort{                                  $response = FroalaEditor_Image::upload('/fro-demos/img/storage/user1/images/');                                  //Ready the request type                repeat stripslashes(json_encode($response));                }                                  catch(Exception $e) {                http_response_code(404);                ?>              

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

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

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

We accept two cases:

  1. Store the last uploaded paradigm only and each time a new image is uploaded it will supplant the old 1. In this instance, all we demand to exercise is to check if the storage folder has an image to brandish. If information technology doesn't have whatsoever paradigm, we volition brandish the placeholder image.
  2. Allowing users to shop multiple images in the storage folder. In this example, you'll need to store besides the uploaded epitome filename to employ in displaying the image afterwards, in a real application you can store the image filename in the users table in the database, merely for this demo we will store it in JSON file at storage\user1\images\image_name.txt.

In this toturial we volition implement the second instance. Open the upload.php file and add together the following line to store the uploaded epitome 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 lawmaking:

                <?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);                //render the response                repeat stripslashes($response);                }                catch (                  Exception $due east) {                                  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 folio is loaded and the image_name.text file has an paradigm proper noun, then the server should display that image, otherwise, the placeholder image should be displayed. The following code is but doing this.

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

                <div class="form-group">                <label for=" "                >Upload Photograph<                /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>     </effigy>     </div>                              

Step 4: Upload Images From URL To The Server

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

  • Prepare the imageCORSProxy option to 'https://cors-anywhere.herokuapp.com'
  • Open up the link https://cors-anywhere.herokuapp.com/corsdemo on a new page
  • Click on "Asking temporary admission to the demo server" button

The message "You currently have temporary access to the demo server." should announced and if you lot render to your upload class, you lot will be able to upload images from URLs

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

Stride v: Setup Image Manager

With Froala, an paradigm managing director 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 volition 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: [                  'prototype', 'imageManager'],                                  //image popup buttons                                  imageEditButtons: ['imageReplace', 'imageRemove'],                                  //Buttons for the popup menu which appears on imageReplace button click                                  imageInsertButtons: ['imageBack', '|', 'imageUpload', 'imageByURL', 'imageManager'],                //Prepare the request blazon                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 paradigm delete URL.                imageManagerDeleteURL:'delete_image.php',                //Set the image upload URL.                imageManagerLoadURL:                    'image_manager.php',                                      });                  </script>                              

In the image_manager.php file you demand merely to telephone call the FroalaEditor_Image::getList function and pass the image storage path every bit the first statement. The Froala SDK volition return an array of the images objects stored in that binder. All you lot demand to practise is to return the images assortment back to the client.

                <?php                                  /** image_manager.php file **/                                  require                  'sdk/lib/FroalaEditor.php',;                                  try {                                  // Go list of the images.                                  $response = FroalaEditor_Image::getList('/fro-demos/img/storage/user1/images/');                                  // return the listing 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, y'all should be able to view your images

  • Set the imageManagerLoadMethod selection if you want to send a different HTTP request types rather than GET.
  • Prototype Manager can brandish images in categories as well. Check the complete imageManager options list to know how to do that.

When y'all hover over an image within the Paradigm Manager, two buttons are shown one is for replacing the contour paradigm with the selected image and the other is for removing the selected paradigm.

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

To do this nosotros need to transport an HTTP asking 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 choice for doing this, only Froala has a variety of events that tin can assist in doing custom requirements.

In our case, we volition use the Froala image.replaced result to ship an HTTP request to the server. At the following code inside the options object of Froala initializing lawmaking

                                  /** The Events object of the Editor initialization code **/                events: {                'prototype.replaced': office ($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 blazon and target url                request.open('Mail service', window.location.pathname+'store_image_link.php', true);                //Prepare the data that volition be sent along with the request                var data=new FormData();                //send the link of the replaced image that needs to get stored                data.suspend('img_link', imgLink);                //send the request with the data                request.onload=function() {                if (this.status >=                    200                    && this.condition                  <                  400) {                //request Success!                                  console.log ('Prototype 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.ship = (data)                request.onerror = function() {                // At that place was a connectedness error of some sort                                  var err = this.response;                                  console.log ('Epitome delete problem: ' + JSON.stringify(err));                                  };                                  }                                  }              

It will transport an HTTP asking to the store_image_link.php file which we volition create at the projection base folder and information technology will incorporate the following code to receive the replaced prototype link and store it within the text file.

                <?php                                  /** store_img_link.php file **/                                  endeavor {                                  //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 customer.                echo stripslashes(json_encode('Success'));                }                catch (Exception $e) {                {            http_response_code(404);                }                ?>              

Since prototype.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 **/                                  endeavour {                                  //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);                //Render success message to the customer.                echo stripslashes(json_encode('Success'));                }                catch (Exception $due east) {                {            http_response_code(404);                }                ?>              

We are now storing the image link directly not every bit 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 paradigm when the page is reloaded should now be working correctly even if it is replaced using the Epitome Manager.

Step 6: Delete Images

Deleting images is done past 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 means

vi.i: 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 prototype popup menu, nosotros will use the epitome.beforeRemove issue to send the request.

If the image is successfully deleted from the server, the client will supplant the current prototype with the placeholder image and alarm the user that image is successfully deleted.

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

                                  /**Adding prototype.beforeRemove issue to the Editor initialization code **/                //delete image from the server                'image.beforeRemove': part ($img){                                //go the paradigm 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('Mail service', window.location.pathname+'store_image_link.php', true);                //Set the data that will exist sent along with the request                var data=new FormData();                //send the link of the replaced paradigm that needs to get stored                data.suspend('src', imgLink);                //send the request with the data                asking.send(data);                request.onload = function() {                if (this.status >=                    200                    && this.condition                  <                  400) {                //Success!                const placeholder = certificate.getElementById('logo');                  placeholder.src                                    "https://i.ibb.co/g9gGYPX/avatar-g177d581fb-640.png";                                      //Display alert to the user                  warning ('Image was successfully deleted');                      }                    else {                    //We reached our target server, merely it returned an fault                    var err = this.response;                    console.log ('Image delete problem: ' + JSON.stringify(err));                    }                 };                    //On request failure                                        request.onerror = office() {                    // At that place was a connexion fault of some sort                    var err = this.response;                    console.log ('Paradigm delete problem: ' + JSON.stringify(err));                                          };                    //return simulated to preclude Froala from removing img src earlier the HTTP asking is completed                    render 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 comprise the following code to delete the image from the server by calling FroalaEditor_Image::delete and set the image link as the beginning argument. It also will delete the image link from the image_name.txt file.

                <?php                                  /** delet_image.php file **/                                  try {                                  //Receive the epitome 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 bulletin to the client.                echo stripslashes(json_encode('Success'));                }                catch (Exception $eastward) {                {            http_response_code(404);                }                ?>              

6.2 Delete Images From Prototype Manager

For deleting images from the ImageManager, Froala provides iii options imageManagerDeleteURL, imageManagerDeleteMethod, and imageManagerDeleteParams. We will utilize the imageManagerDeleteURL option to send an HTTP request to the server when an epitome is deleted. We will the HTTP request to the same delete_image.php file that we accept used in pace 6.1 to delete the selected image from the server. Since ImageManager has multi-images, we demand to bank check if the image that will be deleted is the same one that is used every bit the contour paradigm before removing the image link from the image_name.txt file.

ane. Set the imageManagerDeleteURL pick to delete_image.php

                                  // Ready the paradigm manager delete URL.                                  imageManagerDeleteURL:                    'delete_image.php',                              

2. Edit delete_image.php to become the active profile image link and cheque if it is the same equally the image that will be deleted link. If information technology is and then delete the image link from the image_name.txt file.

                <?php                /*** deleted_image.php file ***/                                  crave                  'sdk/lib/FroalaEditor.php',;                                  try {                //become the image to exist deleted link                $deleted_img_link = $_POST('src');                                  //Delete image from the server                $response = FroalaEditor_Image::delete($deleted_img_link);                                  //Bank check the image link is the profile prototype link or not                //become 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 paradigm is used and it is the ane that will be deleted                if($profile_img_link !== fake && !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', cypher)                     {                //Return a success message to the client.                file_put_contents(json_encode('Success'))                     }                  grab(Exception $eastward) {                                          http_response_code(                      404);                    }                    ?>                                                

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

3. Finally, The customer should supersede the profile image with the placeholder image If the deleted image is the aforementioned as the contour image. To do this nosotros volition utilize the imageManager.imageDeleted event. This event's outset 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 volition be deleted is the profile epitome or not.

                <?php                /*** delet_image.php file ***/                                  require                  'sdk/lib/FroalaEditor.php',;                try {                /** set a flag to point if the image to be deleted is the contour 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 contour image link or not                //get the used contour image                $profile_img_link = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt');                                  //if a profile prototype is used and information technology is the one that volition be deleted                if($profile_img_link !== faux && !empty($profile_img_link) && json_decode($profile_img_link) === $deleted_img_link);                //this is the image used for contour                                  $is_profile_img = true;                //Delete the epitome link from the txt file                file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/fro-demos/img/storage/user1/images/image_name.txt', null)                     }                                  //Render the response to the client.                echo stripslashes(json_encode(["is_profile_img"=>$is_profile_img]));                     }                catch(Exception $due east) {                                      http_response_code(                    404);                  }                  ?>                              

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

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

Pace 7: Paradigm Validation

vii.1: Paradigm Validation On The Client-side

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

Note: Even if y'all are using customer-side validation, server-side validation is also recommended.

7.2: Epitome Validation On The Server-side

In step 3, nosotros 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.

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

Other validations types, e.g. Paradigm size validation can be done past assigning a custom role to the "validation" array.

In our demo, nosotros would allow uploading 'jpeg', 'jpg', and 'png' images only. To do that we will edit upload.php file

                <?php                /**** upload.php file***/                                  crave                  'sdk/lib/FroalaEditor.php',;                try {                $options = assortment(                'validation' => assortment(                'allowedExts' => array('jpeg', 'jpg', 'png'),                  'allowedMimeTypes' => array('prototype/jpeg', 'paradigm/pjpeg', 'image/10-png', 'image/png')                    )                    );                    // Store the image.                    $response = FroalaEditor_Image::upload(/fro-demos/img/storage/user1/images/', $options');                    //return the response                    repeat stripslashes(json_encode($response));                    }                    catch(Exception $east) {                                              http_response_code(                        404);                      }                      ?>                                                                    

Download The Tutorial Total Code

We attain the finish of our tutorial. You tin download the full code form GitHub and get started immediately. If you similar this tutorial please star the GitHub repository, this will encourage us to create more tutorials.

Notwithstanding, our tutorial lawmaking ends hither, nosotros don't cover all what Froala is capable of helping you in. Some of what we didn't cover in the downloaded lawmaking is discussed beneath.

Pace 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 apply image.mistake and imageManager.error events to do then.

Pace ix: Resize Paradigm

9.one: Resize Image On The Customer-Side

Froala allows users to resize the profile image while they are viewing information technology on the browser, but this doesn't affect the physical size of the image. Unless you use Froala events or other means to ship the image size to the server, the epitome volition return to its original size once you lot reload the folio.

9.two: Resize Image On The Server-Side

Froala SDK will help you to automatically resize the uploaded prototype 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 volition thrown.

Pace 10: Upload Images To S3

Froala SDK provides unlike methods to handle uploading images to S3 which will base of operations 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 y'all implementing this.

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

Information technology's common to have a text-area field for assuasive users to enter a description most their profile. Using Froala WYSIWYG editor you can permit your users to improve their description content by allowing them to mode and format their content, Moreover, your users will be able to add together videos, images, tables, and links to get a better profile layout and clarification. All this could be achieved with the same Froala script we have used for paradigm uploading, which ways there are no more than libraries or resources to take care of. and it is easy to be added to your course.

1. Add together the normal textarea field

                <                  div class="class-grouping">  <characterization for="clarification"                  >Clarification<                  /characterization                  >                  <textarea class="grade-control"                  id="description"                  proper noun="clarification"                  placeholder="Enter a contour description"                  >  </textarea>  </div>                                                

ii. Initialize a new editor on it.

                                  new FroalaEditor(                  '#description');                              

smithalings.blogspot.com

Source: https://froala.com/image-uploader/handle-user-profile-image-php-tutorial/

0 Response to "Replace Image by Uploading a New One Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel